本文介紹golang中如何進行反向代理。golang
下面例子中,
proxy server接收client 的 http request,轉發給true server,並把 true server的返回結果再發送給client。curl
proxyServer.go代碼以下所示。url
// proxyServer.go package main import ( "log" "net/http" "net/http/httputil" "net/url" ) //將request轉發給 http://127.0.0.1:2003 func helloHandler(w http.ResponseWriter, r *http.Request) { trueServer := "http://127.0.0.1:2003" url, err := url.Parse(trueServer) if err != nil { log.Println(err) return } proxy := httputil.NewSingleHostReverseProxy(url) proxy.ServeHTTP(w, r) } func main() { http.HandleFunc("/hello", helloHandler) log.Fatal(http.ListenAndServe(":2002", nil)) }
proxyServer監聽端口2002,提供HTTP request "/hello" 的轉發服務。代理
其中,code
func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
NewSingleHostReverseProxy 返回一個新的 ReverseProxy, 將URLs 請求路由到targe的指定的scheme, host, base path 。server
若是target的path是"/base" ,client請求的URL是 "/dir", 則target 最後轉發的請求就是 /base/dir。路由
ReverseProxy 是 HTTP Handler, 接收client的 request,將其發送給另外一個server, 並將server 返回的response轉發給client。get
trueServer.go代碼以下所示。it
// trueServer.go package main import ( "io" "net/http" "log" ) func helloHandler(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", helloHandler) log.Fatal(http.ListenAndServe(":2003", nil)) }
trueServer 做爲一個HTTP server,監聽端口2003,提供"/hello"的實際處理。io
client代碼以下
$ curl http://127.0.0.1:2002/hello hello, world!