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:

  1. Copy the context of the upstream request to the downstream request
  2. Modify requests (such as protocols, parameters, urls, etc.) using the specified director (the function that modifies the request)
  3. Check whether the Upgrade protocol needs to be upgraded based on the request Header[“Connection”]
  4. Delete the hop-by-hop Header in the upstream request to maintain a persistent (relatively) upstream connection without transparent transmission to the downstream
  5. Run the x-forward-for Header command to append the IP address of the current node
  6. Use connection pooling to make requests downstream
  7. Handling httpcode 101 protocol upgrades :(WebSocket, h2c, etc.)
  8. Delete the hop-by-hop Header from the request and do not return it upstream
  9. According to the structure ReverseProxy. ModifyResponse (function) determine whether modify the content of the response body
  10. Copies the downstream response header to the upstream response request
  11. Returns the downstream request HTTP status code
  12. Copy the downstream response content to the upstream response request
  13. Refresh the content to Response

Other source

NewSingleHostReverseProxy function

NewSingleHostReverseProxy URL in stitching method