net/http/httputil

Guided tour · Networking · pkg.go.dev →

Utilities on top of net/http: reverse proxy, dump request/response, chunked encoding.

ReverseProxy — transparent HTTP proxying

NewSingleHostReverseProxy

A few lines gets you a real reverse proxy. Wrap with middleware for logging, auth, or header rewriting.

target, _ := url.Parse("http://backend:8080")
proxy := httputil.NewSingleHostReverseProxy(target)

http.Handle("/", proxy)
http.ListenAndServe(":80", nil)

Customize with Rewrite (1.20+)

proxy := &httputil.ReverseProxy{
    Rewrite: func(r *httputil.ProxyRequest) {
        r.SetURL(target)
        r.Out.Header.Set("X-Forwarded-Host", r.In.Host)
    },
}

Dumping requests and responses

DumpRequest / DumpResponse — debug the wire format

b, _ := httputil.DumpRequest(r, true)
fmt.Println(string(b))