我正在使用httputil.ReverseProxy将Amazon s3文件代理到我的客户端。我想隐藏所有来自亚马逊的标题 - 这是否可能而不必重新实现反向代理?
proxy := httputil.ReverseProxy{Director: func(r *http.Request) {
r.Header = http.Header{} // Don't send client's request headers to Amazon.
r.URL = proxyURL
r.Host = proxyURL.Host
}}
proxy.ServeHTTP(w, r) // How do I remove w.Headers ?
答案 0 :(得分:3)
您可以实施ReverseProxy.Transport
type MyTransport struct{
header http.Header
}
func (t MyTransport) RoundTrip(r *Request) (*Response, error){
resp, err := http.DefaultTransport.RoundTrip(r)
resp.Header = t.header
return resp, err
}
mytransport := MyTransport{
//construct Header
}
proxy := httputil.ReverseProxy{Director: func(r *http.Request) {
r.Header = http.Header{} // Don't send client's request headers to Amazon.
r.URL = proxyURL
r.Host = proxyURL.Host
},
Transport: mytransport,
}
答案 1 :(得分:1)
这是我删除/替换所有http.ReverseProxy响应头的解决方案:
type responseHeadersTransport http.Header
func (t responseHeadersTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := http.DefaultTransport.RoundTrip(r)
if err != nil {
return nil, err
}
resp.Header = http.Header(t)
return resp, nil
}
func ProxyFile(w http.ResponseWriter, r *http.Request) {
// ...
headers := http.Header{}
headers.Set("Content-Type", file.ContentType)
headers.Set("Content-Length", fmt.Sprintf("%d", file.Filesize))
headers.Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", file.Filename))
proxy := httputil.ReverseProxy{
Director: func(r *http.Request) { // Remove request headers.
r.Header = http.Header{}
r.URL = proxyURL
r.Host = proxyURL.Host
},
Transport: responseHeadersTransport(headers), // Replace response headers.
}
proxy.ServeHTTP(w, r)
}