Standard library / net/http/httputil

httputil.NewSingleHostReverseProxy()

Build a proxy with a legacy Director routing to the fixed target; retains inbound Host and may append untrusted forwarding values. Prefer an explicit Rewrite with a defined trust policy for new services. Expected stdout: '/base/a\n'.

Formal Syntax & Structure

go syntaxgo
func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

Parameters & Attributes

NameTypeDescription
target*url.URLFixed backend URL including scheme, host and optional base path.

Return Value

*ReverseProxy

Reverse proxy handler with a Director that routes to target.

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.NewSingleHostReverseProxy(target)  w := httptest.NewRecorder()  p.ServeHTTP(w, httptest.NewRequest("GET", "/a", nil))  fmt.Println(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