Reverse Proxy Handler
Forward requests with httputil.ReverseProxy, add a forwarded-host header, strip internal headers, and return 502 on failure.
Code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strings"
)
func NewReverseProxy(target *url.URL) *httputil.ReverseProxy {
proxy := httputil.NewSingleHostReverseProxy(target)
originalDirector := proxy.Director
proxy.Director = func(request *http.Request) {
originalDirector(request)
request.Header.Set("X-Forwarded-Host", request.Host)
request.Header.Del("X-Internal-Debug")
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
fmt.Println("proxy error:", err)
http.Error(w, "upstream unavailable", http.StatusBadGateway)
}
return proxy
}
func main() {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "path=%s host=%s", r.URL.Path, r.Header.Get("X-Forwarded-Host"))
}))
defer backend.Close()
target, err := url.Parse(backend.URL)
if err != nil {
panic(err)
}
front := httptest.NewServer(NewReverseProxy(target))
defer front.Close()
response, err := http.Get(front.URL + "/api/items?page=2")
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println("status:", response.StatusCode)
fmt.Println("body:", strings.TrimSpace(string(body)))
}How the run unfolds
Everything that executes sits inside the functions NewReverseProxy and main.
Failure handling is panic(err): 3 checkpoints abort the program at the point a problem is detected. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
What to watch for
- Adapting this to library code usually means replacing the
panic(err)calls with error returns the caller can branch on.
Putting it to use
The one signature that matters here is func NewReverseProxy(target *url.URL) *httputil.ReverseProxy
The demo output is labeled (proxy error:, status:, body:), so the output doubles as a step-by-step trace of what the file did.
Execute the file and main walks through NewReverseProxy, in that order.
Core lines
if err != nil {
panic(err)
}
defer response.Body.Close()
defer backend.Close()
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
- What does Reverse Proxy Handler print when run?
- Execute the whole file; each printed line is prefixed with a label like `proxy error:`, `status:`, `body:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.