This is the 13th day of my participation in Gwen Challenge
If ❤️ my article is helpful, welcome to like, follow. This is the biggest encouragement for me to continue my technical creation. More articles in this series are on my blog
Preliminary study on Golang ReverseProxy source code
Golang version 1.16
An example of using ReverseProxy to implement ReverseProxy
Talk is cheap, show me the code
Testing the proxy server
$ curl 'http://127.0.0.1:2002/sda? sda=111'
Upath := fmt.sprintf ("http://%s%s\n", r.adddr, req.url.path)http://127.0.0.1:2003/base/sda RemoteAddr = 127.0.0.1:51738, X - Forwarded - For = 127.0.0.1, X-ray Real - Ip headers of = = map [Accept: * / * The Accept - Encoding: [gzip] the user-agent: curl / 7.69.1 X-ray Forwarded - For: [127.0.0.1]]Copy the code
See httputil. NewSingleHostReverseProxy () function, can find ReverseProxy source code. Located in the directory file go/SRC/net/HTTP/httputil reverseproxy. Go
The core source
ReverseProxy structure
ServeHTTP()
ReverseProxy implements the ServeHTTP() method, which is eventually called on ListenAndServe() when the request arrives at the proxy server. The call link is:
http.ListenAndServe(addr string, handler Handler)
-> Server.ListenAndServeTLS(certFile, keyFile)
-> Server.ServeTLS(ln, certFile, keyFile)
-> Server.Serve(l net.Listener)
-> go c.serve(connCtx)
-> serverHandler{c.server}.ServeHTTP(w, w.req)
Copy the code
Therefore, the ReverseProxy structure also implements the ServeHTTP method, which has the following functions:
- Copy the context of the upstream request to the downstream request
- Modify requests (such as protocols, parameters, urls, etc.) using the specified director (the function that modifies the request)
- Check whether the Upgrade protocol needs to be upgraded based on the request Header[“Connection”]
- Delete the hop-by-hop Header in the upstream request to maintain a persistent (relatively) upstream connection without transparent transmission to the downstream
- Run the x-forward-for Header command to append the IP address of the current node
- Use connection pooling to make requests downstream
- Handling httpcode 101 protocol upgrades :(WebSocket, h2c, etc.)
- Delete the hop-by-hop Header from the request and do not return it upstream
- According to the structure ReverseProxy. ModifyResponse (function) determine whether modify the content of the response body
- Copies the downstream response header to the upstream response request
- Returns the downstream request HTTP status code
- Copy the downstream response content to the upstream response request
- Refresh the content to Response