本文介绍golang中如何进行反向代理。golang

下面例子中,
proxy server接收client 的 http request,转发给true server,并把 true server的返回结果再发送给client。curl

1.proxy server

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

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

NewSingleHostReverseProxy 返回一个新的 ReverseProxy, 将URLs 请求路由到targe的指定的scheme, host, base path 。server

若是target的path是"/base" ,client请求的URL是 "/dir", 则target 最后转发的请求就是 /base/dir。路由

type ReverseProxy

ReverseProxy 是 HTTP Handler, 接收client的 request,将其发送给另外一个server, 并将server 返回的response转发给client。get

2.true server

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

3.client

client代码以下

$ curl http://127.0.0.1:2002/hello
hello, world!
参考