Standard library / net/http/httputil

httputil.ReverseProxy

An HTTP handler that forwards requests to a configured backend. Rewrite or Director (not both) configures routing; prefer Rewrite for clear forwarded-header boundaries. Transport controls backend requests, FlushInterval controls periodic flushing, BufferPool supplies copy buffers, ErrorLog receives diagnostics, ModifyResponse can change a backend response and ErrorHandler handles failures. Expected stdout: '200 /base/a\n'.

Formal Syntax & Structure

go syntaxgo
type ReverseProxy struct {  Rewrite func(*ProxyRequest)
  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)}

Working Example

Example Snippetgo
package main
import (  "fmt"  "net/http"  "net/http/httptest"  "net/http/httputil"  "net/url")
func main() {  s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, r.URL.Path) }))  defer s.Close()  target := must(url.Parse(s.URL + "/base"))  p := &httputil.ReverseProxy{Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(target); r.SetXForwarded() }}  w := httptest.NewRecorder()  p.ServeHTTP(w, httptest.NewRequest("GET", "/a", nil))  fmt.Println(w.Code, w.Body.String())}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference