Implementing a Reverse Proxy in Go with Custom Enhancements
This article explains the concept of reverse proxies, demonstrates a basic Go implementation using net/http's ReverseProxy, analyzes the official ReverseProxy structure, and provides a custom wrapper that adds tracing, timeout handling, logging, error processing, and transport tuning for production-ready backend services.
Background: a reverse proxy acts as an intermediary between a client and a target server; Go's net/http package provides a built‑in ReverseProxy but its capabilities are limited for production needs.
Simple usage shows how to parse the target URL, instantiate httputil.NewSingleHostReverseProxy, and start an HTTP server.
target, err := url.Parse("http://www.domain.com")</code>
<code>if err != nil { panic(err) }</code>
<code>proxy := httputil.NewSingleHostReverseProxy(target)</code>
<code>log.Fatal(http.ListenAndServe(":8082", proxy))The official ReverseProxy struct contains fields such as Director, Transport, FlushInterval, ErrorLog, BufferPool, ModifyResponse, and ErrorHandler, each responsible for different aspects of request forwarding and response handling.
type ReverseProxy struct { Director func(*http.Request); Transport http.RoundTripper; FlushInterval time.Duration; ErrorLog *log.Logger; BufferPool BufferPool; ModifyResponse func(*http.Response) error; ErrorHandler func(http.ResponseWriter, *http.Request, error) }Initialization via NewSingleHostReverseProxy sets the request scheme, host, path, query string, and clears the default User-Agent header to avoid unwanted defaults.
func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy { /* sets target scheme, host, path, query, and User-Agent */ }The core ServeHTTP method clones the incoming request, manages context cancellation, adjusts headers (including removal of hop headers and addition of X-Forwarded-For), handles protocol upgrades, forwards the request using the configured transport, processes the response, copies headers, writes the status code, streams the body, and flushes trailers when needed.
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { /* request cloning, header manipulation, transport.RoundTrip, response handling */ }A custom ServeHTTP wrapper is introduced to provide tracing, timeout extraction, structured logging, and custom error/response handling while still leveraging the underlying ReverseProxy for actual forwarding.
type ServeHTTP struct { targetUrl string; reverseProxy *httputil.ReverseProxy; proxyErrorHandler ProxyErrorHandler; logger log.Logger }Transport tuning demonstrates increasing MaxIdleConns and MaxIdleConnsPerHost to 200 to improve performance under HTTP/1.1 workloads.
netHttp.Transport{ MaxIdleConns: 200, MaxIdleConnsPerHost: 200, IdleConnTimeout: 90*time.Second, /* other fields */ }Utility functions generate a trace ID, determine request timeout, log detailed request/response information, and set appropriate response headers, illustrating a complete, production‑ready reverse‑proxy solution in Go.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
TAL Education Technology
TAL Education is a technology-driven education company committed to the mission of 'making education better through love and technology'. The TAL technology team has always been dedicated to educational technology research and innovation. This is the external platform of the TAL technology team, sharing weekly curated technical articles and recruitment information.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
