Standard library / net/http/httputil

httputil.ReverseProxy.ServeHTTP()

Forward the incoming request and copy the backend response. Hop-by-hop headers are removed; backend transport failures go to ErrorHandler or the default 502 handler. Expected stdout: '200 yes /base/a\n'.

Formal Syntax & Structure

go syntaxgo
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)

Parameters & Attributes

NameTypeDescription
rwhttp.ResponseWriterResponse writer for this active incoming request.
req*http.RequestHTTP request to inspect or exchange. Use only synthetic data in dumps.

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) }, ModifyResponse: func(r *http.Response) error { r.Header.Set("X-Demo", "yes"); return nil }}  w := httptest.NewRecorder()  p.ServeHTTP(w, httptest.NewRequest("GET", "/a", nil))  fmt.Println(w.Code, w.Header().Get("X-Demo"), 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