This is a creation in Article, where the information may have evolved or changed.
Look at the Golang bag manual when you see Net/http/httputil there is a type reverseproxy, this is not a reverse proxy it! Golang comes with reverse proxy function? Curiosity to try, it is very simple, not a few lines of code to achieve a simple reverse proxy service.
About reverse proxy Baidu Encyclopedia said very detailed, here excerpt the definition:
The reverse proxy method refers to a proxy server that accepts connection requests on the Internet, then forwards the request to a server on the internal network and returns the results from the server to the client requesting the connection on the Internet, Reverse. At this point the proxy server appears as a reverse proxy server externally.
Golang Implementation Code
Package Mainimport ("Log", "Net/http" "Net/http/httputil" "Net/url") type handle struct {host Stringport string}func (this * HANDLE) servehttp (w http. Responsewriter, R *http. Request) {remote, err: = URL. Parse ("http://" + This.host + "+" + this.port) if err! = Nil {panic (err)}proxy: = Httputil. Newsinglehostreverseproxy (remote) proxy. Servehttp (W, R)}func StartServer () {//proxy server host and Porth: = &handle{host: "127.0.0.1", Port: "W"}err: = http. Listenandserve (": 8888", h) if err! = Nil {log. Fatalln ("Listenandserve:", err)}}func main () {StartServer ()}
The key code is Newsinglehostreverseproxy this method, look at the source word is not difficult to see the method returned a Reverseproxy object, in Reverseproxy Servehttp method to achieve this specific process, The primary is to reseal the source HTTP header and then send it to the back-end server.