4

I'm using httputil.ReverseProxy to proxy Amazon s3 files to my clients. I'd like to hide all headers coming from Amazon - is that possible without having to reimplement Reverse Proxy?

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 ?
1
  • Unfortunately ResponseWriter is an interface and only exposes a getter for the Header collection so I don't think there is any simple way to do this. You could iterate the collection and set them all to "null" but that's a poor substitute for something like w.Headers = nil... Commented May 3, 2016 at 21:12

2 Answers 2

5

You can implement 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,
}
Sign up to request clarification or add additional context in comments.

Comments

3

This was my solution to remove/replace all the http.ReverseProxy response headers:

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.