如何使用golang实现可透传原请求的header的反向代理?

使用golang中的func NewSingleHostReverseProxy(target url.URL) ReverseProxy {} 可以实现反向代理,但是查看该法的的源码发现,这种代理是不会带上原请求的header中各值对的,有什么好办法可以通过golang实现反向代理同时也会带上原请求的header?【问题场景:原始请求的相关参数(如 http Authorization的授权认证是 通过 header 传递的,这点不得改变——即必须保留对这种做法的支持】

已邀请:

dcb9

赞同来自:

httputil.NewSingleHostReverseProxy 是会保留 Header 的啊。 我看到的源码是:

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
    targetQuery := target.RawQuery
    director := func(req *http.Request) {
        req.URL.Scheme = target.Scheme
        req.URL.Host = target.Host
        req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
        if targetQuery == "" || req.URL.RawQuery == "" {
            req.URL.RawQuery = targetQuery + req.URL.RawQuery
        } else {
            req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
        }
        if _, ok := req.Header["User-Agent"]; !ok {
            // explicitly disable User-Agent so it's not set to default value
            req.Header.Set("User-Agent", "")
        }
    }
    return &ReverseProxy{Director: director}
}

我写了一个 reverseproxy_test.go 内容如下:

package reverseproxy

import (
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "net/url"
    "testing"
)

func TestRP(t *testing.T) {
    backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        t.Log("headers: ", r.Header)
    }))

    target, _ := url.Parse(backendServer.URL)
    reverseProxy := httputil.NewSingleHostReverseProxy(target)
    proxyServer := httptest.NewServer(reverseProxy)

    req, err := http.NewRequest("POST", proxyServer.URL+"/", nil)
    if err != nil {
        t.Fatal(err)
    }
    req.Header.Set("Authorization", "abcdefg")

    _, err = http.DefaultClient.Do(req)
    if err != nil {
        t.Fatal(err)
    }
}

然后运行 go test -v reverseproxy_test.go 已经得到了请求时的 Header 信息

=== RUN   TestRP
--- PASS: TestRP (0.00s)
    reverseproxy_test.go:13: headers:  map[User-Agent:[Go-http-client/1.1] Content-Length:[0] Accept-Encoding:[gzip] Authorization:[abcdefg] X-Forwarded-For:[127.0.0.1]]
PASS
ok      command-line-arguments  0.015s

要回复问题请先登录注册