Standard library / net/http/httputil
httputil.ProxyRequest.SetXForwarded()
Set X-Forwarded-For from the incoming remote IP, X-Forwarded-Host from the incoming Host and X-Forwarded-Proto from TLS presence. Existing outbound X-Forwarded-For is appended to, so only preserve values from trusted proxies. Expected stdout: '192.0.2.7 demo.invalid https\n'.
Formal Syntax & Structure
go syntaxgo
func (r *ProxyRequest) SetXForwarded()Working Example
Example Snippetgo
package main
import ( "fmt" "net/http/httptest" "net/http/httputil")
func main() { in := httptest.NewRequest("GET", "https://demo.invalid/a", nil) in.RemoteAddr = "192.0.2.7:12345" p := httputil.ProxyRequest{In: in, Out: in.Clone(in.Context())} p.SetXForwarded() fmt.Println(p.Out.Header.Get("X-Forwarded-For"), p.Out.Header.Get("X-Forwarded-Host"), p.Out.Header.Get("X-Forwarded-Proto"))}
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) }}