HTTP headers
suggest changeEvery HTTP request and response carries a list of headers: Name: value lines sent before the body. They describe the body (Content-Type, Content-Length), carry credentials (Authorization, Cookie), control caching (Cache-Control, ETag) and much more.
In Go, all of this lives in net/http:
http.Headeris the type that holds headersr.Headerholds the headers of an incoming request in a handlerw.Header()holds the headers of the response you're about to sendreq.Headerandresp.Headerare the same thing on the client side
This article covers working with headers on both sides. Cookies have their own article: Cookies.
The http.Header type
http.Header is defined as map[string][]string. A header name can appear more than once, so each key maps to a slice of values.
HTTP header names are case-insensitive. Go handles that by storing keys in canonical form: the first letter and every letter after a hyphen is upper case, the rest are lower case (content-type becomes Content-Type). The methods canonicalize the name you pass them:
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
h := http.Header{}
h.Set("content-type", "text/plain")
h.Add("Accept", "text/html")
h.Add("accept", "application/json")
h.Set("x-request-id", "abc123")
fmt.Println(h.Get("Content-Type"))
fmt.Println(h.Get("ACCEPT")) // only the first value
fmt.Println(h.Values("Accept")) // all values
fmt.Printf("%q\n", h.Get("X-Missing"))
// http.Header is map[string][]string with canonical keys
fmt.Println(h["Accept"])
fmt.Println(h["accept"]) // direct map access is not canonicalized
h.Del("x-request-id")
fmt.Println(len(h))
fmt.Println(http.CanonicalHeaderKey("x-forwarded-for"))
fmt.Println(http.CanonicalHeaderKey("WWW-AUTHENTICATE"))
// Write outputs headers in wire format, sorted by key
h.Write(os.Stdout)
}
text/plain
text/html
[text/html application/json]
""
[text/html application/json]
[]
2
X-Forwarded-For
Www-Authenticate
Accept: text/html
Accept: application/json
Content-Type: text/plain
The methods:
| method | does |
|---|---|
Set(k, v) |
replaces all values of k with v |
Add(k, v) |
appends v to the values of k |
Get(k) |
returns the first value, or "" if missing |
Values(k) |
returns all values |
Del(k) |
removes all values of k |
Clone() |
returns a deep copy |
Write(w) |
writes headers in wire format |
Two things to remember:
Getreturns""both when a header is missing and when it's present with an empty value. If you need to tell them apart, check the map directly:_, ok := h["X-Foo"].- Indexing the map directly (
h["accept"]) does not canonicalize the key. Use the methods, or make sure you use the canonical spelling. This also meansETagis stored asEtagandWWW-AuthenticateasWww-Authenticate. HTTP/1.1 doesn't care about case and HTTP/2 sends names in lower case, so this is only a problem when you look at the map yourself.
Reading request headers in a handler
In a handler the request headers are in r.Header:
package main
import (
"fmt"
"io"
"log"
"maps"
"net/http"
"net/http/httptest"
"slices"
"strings"
)
func handler(w http.ResponseWriter, r *http.Request) {
// print all headers, sorted by name
for _, name := range slices.Sorted(maps.Keys(r.Header)) {
fmt.Fprintf(w, "%s: %q\n", name, r.Header[name])
}
// Host is not in r.Header, it's moved to r.Host
fmt.Fprintf(w, "r.Host is host:port: %v\n", strings.HasPrefix(r.Host, "127.0.0.1:"))
fmt.Fprintf(w, "Header has Host: %v\n", r.Header.Get("Host") != "")
// a single header line can contain a comma-separated list
for _, v := range r.Header.Values("Accept") {
for part := range strings.SplitSeq(v, ",") {
fmt.Fprintf(w, "accept part: %s\n", strings.TrimSpace(part))
}
}
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
req, err := http.NewRequest("GET", srv.URL, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Accept", "text/html, application/json;q=0.9")
req.Header.Add("X-Tag", "one")
req.Header.Add("X-Tag", "two")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Print(string(body))
}
Accept: ["text/html, application/json;q=0.9"]
Accept-Encoding: ["gzip"]
User-Agent: ["Go-http-client/1.1"]
X-Tag: ["one" "two"]
r.Host is host:port: true
Header has Host: false
accept part: text/html
accept part: application/json;q=0.9
Things to notice:
- the Go client added
User-AgentandAccept-Encodingby itself Hostis not inr.Header. The server removes it and puts it inr.Host- when the client sends the same header twice (
X-Tag), you get both values - a header can also hold a comma-separated list in a single line (
Accept).Valuesdoesn't split it, so you have to do it yourself
A few common headers have their own helpers on *http.Request: r.UserAgent(), r.Referer(), r.Cookie(name), r.BasicAuth(), and r.ContentLength for Content-Length.
Setting response headers
Response headers are set on the map returned by w.Header(). The order of calls matters: headers are sent when you call w.WriteHeader or the first w.Write. Changes made after that are ignored.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
)
func good(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Header().Add("X-Feature", "a")
w.Header().Add("X-Feature", "b")
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"ok":true}`)
}
func bad(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
// too late: headers were already sent with WriteHeader
w.Header().Set("X-Too-Late", "yes")
fmt.Fprint(w, "<html><body>hi</body></html>")
}
func show(url string) {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println("status: ", resp.StatusCode)
fmt.Println("Content-Type: ", resp.Header.Get("Content-Type"))
fmt.Println("Content-Length:", resp.Header.Get("Content-Length"))
fmt.Println("Cache-Control: ", resp.Header.Get("Cache-Control"))
fmt.Println("X-Feature: ", resp.Header.Values("X-Feature"))
fmt.Println("X-Too-Late: ", resp.Header.Get("X-Too-Late"))
fmt.Println("has Date: ", resp.Header.Get("Date") != "")
fmt.Println()
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/good", good)
mux.HandleFunc("/bad", bad)
srv := httptest.NewServer(mux)
defer srv.Close()
show(srv.URL + "/good")
show(srv.URL + "/bad")
}
status: 201
Content-Type: application/json
Content-Length: 11
Cache-Control: no-store
X-Feature: [a b]
X-Too-Late:
has Date: true
status: 200
Content-Type: text/html; charset=utf-8
Content-Length: 28
Cache-Control:
X-Feature: []
X-Too-Late:
has Date: true
In the bad handler X-Too-Late was never sent. go vet doesn't catch this, so the rule is: set all headers first, then call WriteHeader, then write the body.
The server also fills in a few headers for you:
Dateis always setContent-Lengthis set when the handler writes a small body and returns without flushing. Otherwise the response is sent withTransfer-Encoding: chunkedContent-Type: if you don't set it, Go sniffs the first 512 bytes of the body withhttp.DetectContentType. That's howbadgottext/html; charset=utf-8. Sniffing is a guess, so setContent-Typeexplicitly for anything that's not plain HTML. For JSON in particular, sniffing givestext/plain; charset=utf-8
To stop the server from adding a header at all, set it to nil: w.Header()["Date"] = nil.
Setting request headers in a client
On the client side you set headers on req.Header before calling client.Do. The http.Get and http.Post shortcuts don't let you set headers, so you need http.NewRequest (or http.NewRequestWithContext). Set User-Agent shows the basic case.
When every request made with a client needs the same headers (an API token, a User-Agent), wrap the transport instead of repeating req.Header.Set everywhere:
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
)
// headerTransport adds headers to every request made with a client
type headerTransport struct {
base http.RoundTripper
headers http.Header
}
func (t *headerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// a RoundTripper must not modify the request it was given
req = req.Clone(req.Context())
for k, vals := range t.headers {
if req.Header.Get(k) == "" {
req.Header[k] = vals
}
}
return t.base.RoundTrip(req)
}
func echo(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Host: %s\n", r.Host)
fmt.Fprintf(w, "User-Agent: %s\n", r.UserAgent())
fmt.Fprintf(w, "Authorization: %s\n", r.Header.Get("Authorization"))
fmt.Fprintf(w, "Accept: %s\n", r.Header.Get("Accept"))
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(echo))
defer srv.Close()
client := &http.Client{
Transport: &headerTransport{
base: http.DefaultTransport,
headers: http.Header{
"User-Agent": {"my-app/1.0"},
"Authorization": {"Bearer secret-token"},
"Accept": {"application/json"},
},
},
}
req, err := http.NewRequest("GET", srv.URL, nil)
if err != nil {
log.Fatal(err)
}
// per-request header wins over the default
req.Header.Set("Accept", "text/plain")
// Host header is set via req.Host, not req.Header
req.Host = "api.example.com"
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Print(string(body))
}
Host: api.example.com
User-Agent: my-app/1.0
Authorization: Bearer secret-token
Accept: text/plain
Notes:
- a
RoundTrippermust not modify the request it was given, which is why it clones it first - to send a different
Hostheader than the one in the URL, setreq.Host. Settingreq.Header["Host"]is ignored - the transport adds
Accept-Encoding: gzipand transparently decompresses the response. If you setAccept-Encodingyourself, decompression is your job.resp.Uncompressedtells you whether the transport did it - when the client follows a redirect, it copies your headers to the new request, except for
Authorization,WWW-AuthenticateandCookiewhen the redirect goes to a different domain
Reading response headers in a client
resp.Header works the same way as r.Header on the server. Some headers are also parsed into fields of *http.Response:
| field | header |
|---|---|
resp.ContentLength |
Content-Length (-1 when unknown) |
resp.TransferEncoding |
Transfer-Encoding |
resp.Cookies() |
Set-Cookie |
resp.Location() |
Location |
resp.Trailer |
trailers, see below |
Parsing header values
Many header values have a structure: parameters after ;, quoted strings, dates. Don't parse them with strings.Split; the standard library has parsers for the common formats:
package main
import (
"fmt"
"mime"
"net/http"
"strings"
"time"
)
func main() {
// Content-Type: media type plus parameters
mt, params, err := mime.ParseMediaType("text/HTML; charset=UTF-8")
fmt.Println(mt, params, err)
// Content-Disposition uses the same syntax
_, params, _ = mime.ParseMediaType(`attachment; filename="report 2026.pdf"`)
fmt.Println(params["filename"])
// build a header value with correct quoting
fmt.Println(mime.FormatMediaType("attachment", map[string]string{"filename": "my report.pdf"}))
// dates in headers (Date, Last-Modified, Expires) use http.TimeFormat, always in GMT
t := time.Date(2026, 10, 17, 14, 30, 0, 0, time.FixedZone("CEST", 2*3600))
s := t.UTC().Format(http.TimeFormat)
fmt.Println(s)
parsed, err := http.ParseTime(s)
fmt.Println(parsed, err)
// ParseTime also accepts the obsolete RFC 850 and ANSI C formats
parsed, _ = http.ParseTime("Sat Oct 17 12:30:00 2026")
fmt.Println(parsed)
// Authorization: Bearer <token>
r, _ := http.NewRequest("GET", "http://example.com", nil)
r.Header.Set("Authorization", "Bearer eyJhbGciOi")
if token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer "); ok {
fmt.Println("token:", token)
}
// Authorization: Basic base64(user:password)
r.SetBasicAuth("alice", "s3cret")
fmt.Println(r.Header.Get("Authorization"))
user, pass, ok := r.BasicAuth()
fmt.Println(user, pass, ok)
}
text/html map[charset:UTF-8] <nil>
report 2026.pdf
attachment; filename="my report.pdf"
Sat, 17 Oct 2026 12:30:00 GMT
2026-10-17 12:30:00 +0000 UTC <nil>
2026-10-17 12:30:00 +0000 UTC
token: eyJhbGciOi
Basic YWxpY2U6czNjcmV0
alice s3cret true
mime.ParseMediaTypeparsesContent-TypeandContent-Disposition, lower-cases the type and handles quoted parametersmime.FormatMediaTypeis the reverse and quotes values when neededhttp.TimeFormatis the date format used byDate,Last-Modified,ExpiresandIf-Modified-Since. The time must be in UTCr.BasicAuth()andreq.SetBasicAuth()handle the base64 encoding ofAuthorization: Basic
Caching and conditional requests
Cache-Control tells browsers and proxies how long they may reuse a response. ETag and Last-Modified let a client ask "send it only if it changed" with If-None-Match and If-Modified-Since. If it didn't change, the server replies 304 Not Modified with no body.
You don't have to implement this logic. http.ServeContent (and http.ServeFile, http.FileServer) handles conditional and range requests:
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"net/http"
"net/http/httptest"
"time"
)
var (
content = []byte("body { color: navy; }\n")
modTime = time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
etag = makeETag(content)
)
// strong ETag: a quoted string that changes when the content changes
func makeETag(d []byte) string {
sum := sha256.Sum256(d)
return fmt.Sprintf(`"%x"`, sum[:8])
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "public, max-age=3600")
// ServeContent handles If-None-Match, If-Modified-Since, Range
// and sets Content-Type, Content-Length and Last-Modified
http.ServeContent(w, r, "site.css", modTime, bytes.NewReader(content))
}
func do(name string, hdr map[string]string) {
r := httptest.NewRequest("GET", "/site.css", nil)
for k, v := range hdr {
r.Header.Set(k, v)
}
w := httptest.NewRecorder()
handler(w, r)
res := w.Result()
fmt.Printf("%s: %d, %d body bytes\n", name, res.StatusCode, w.Body.Len())
for _, k := range []string{"Content-Type", "Content-Length", "Last-Modified", "ETag", "Content-Range"} {
if v := res.Header.Get(k); v != "" {
fmt.Printf(" %s: %s\n", k, v)
}
}
}
func main() {
do("first request", nil)
do("If-None-Match", map[string]string{"If-None-Match": etag})
do("If-Modified-Since", map[string]string{"If-Modified-Since": "Fri, 02 Oct 2026 00:00:00 GMT"})
do("Range", map[string]string{"Range": "bytes=0-3"})
}
first request: 200, 22 body bytes
Content-Type: text/css; charset=utf-8
Content-Length: 22
Last-Modified: Thu, 01 Oct 2026 08:00:00 GMT
ETag: "b697f4074f38744e"
If-None-Match: 304, 0 body bytes
ETag: "b697f4074f38744e"
If-Modified-Since: 304, 0 body bytes
ETag: "b697f4074f38744e"
Range: 206, 4 body bytes
Content-Type: text/css; charset=utf-8
Content-Length: 4
Last-Modified: Thu, 01 Oct 2026 08:00:00 GMT
ETag: "b697f4074f38744e"
Content-Range: bytes 0-3/22
Typical Cache-Control values:
| value | meaning |
|---|---|
no-store |
never cache (private or sensitive data) |
no-cache |
may store, but must revalidate with the server every time |
private, max-age=60 |
only the browser may cache, for 60 seconds |
public, max-age=31536000, immutable |
cache for a year; use for files with a hash in the name |
httptest.NewRecorder was used here to call the handler directly, without a network connection. It's the easiest way to test handlers that set headers; see Testing HTTP requests.
Trailers
Trailers are headers sent after the body. They're useful for values you only know at the end, like a checksum of streamed data. Announce their names in the Trailer header before writing the body, and set the values after:
package main
import (
"crypto/sha256"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
)
func handler(w http.ResponseWriter, r *http.Request) {
// announce trailers before writing the body
w.Header().Set("Trailer", "X-Checksum, X-Row-Count")
w.Header().Set("Content-Type", "text/plain")
h := sha256.New()
out := io.MultiWriter(w, h)
rows := 0
for i := 1; i <= 3; i++ {
fmt.Fprintf(out, "row %d\n", i)
rows++
}
// set trailer values after the body has been written
w.Header().Set("X-Checksum", fmt.Sprintf("%x", h.Sum(nil)[:8]))
w.Header().Set("X-Row-Count", fmt.Sprint(rows))
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handler))
defer srv.Close()
resp, err := http.Get(srv.URL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// before the body is read, trailer keys are known but values are nil
fmt.Println("before:", resp.Trailer)
fmt.Println("Transfer-Encoding:", resp.TransferEncoding)
body, _ := io.ReadAll(resp.Body)
fmt.Print(string(body))
fmt.Println("X-Checksum: ", resp.Trailer.Get("X-Checksum"))
fmt.Println("X-Row-Count:", resp.Trailer.Get("X-Row-Count"))
}
before: map[X-Checksum:[] X-Row-Count:[]]
Transfer-Encoding: [chunked]
row 1
row 2
row 3
X-Checksum: 6e7cfae5b3dfea0c
X-Row-Count: 3
On the client, resp.Trailer holds the announced keys right away, but the values are filled in only after the body has been read to the end.
A handler can also set trailers it didn't announce by prefixing the name with http.TrailerPrefix: w.Header().Set(http.TrailerPrefix+"X-Checksum", sum).
CORS headers
A browser won't let JavaScript on https://app.example.com read a response from your API on another origin unless the API allows it with Access-Control-* headers. For requests other than simple GETs and POSTs, the browser first sends an OPTIONS "preflight" request asking which methods and headers are allowed.
A minimal CORS middleware:
package main
import (
"fmt"
"maps"
"net/http"
"net/http/httptest"
"slices"
"strings"
)
var allowedOrigins = []string{"https://app.example.com", "https://admin.example.com"}
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
// the response depends on Origin, so caches must key on it
h.Add("Vary", "Origin")
origin := r.Header.Get("Origin")
if origin == "" || !slices.Contains(allowedOrigins, origin) {
next.ServeHTTP(w, r)
return
}
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Expose-Headers", "X-Request-Id")
// preflight request sent by the browser before the real one
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
h.Add("Vary", "Access-Control-Request-Method")
h.Add("Vary", "Access-Control-Request-Headers")
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
h.Set("Access-Control-Max-Age", "600")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func api(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Request-Id", "req-42")
fmt.Fprintln(w, "data")
}
func do(method, origin string, extra map[string]string) {
r := httptest.NewRequest(method, "/api/items", nil)
if origin != "" {
r.Header.Set("Origin", origin)
}
for k, v := range extra {
r.Header.Set(k, v)
}
w := httptest.NewRecorder()
cors(http.HandlerFunc(api)).ServeHTTP(w, r)
fmt.Printf("%s from %q -> %d\n", method, origin, w.Code)
for _, k := range slices.Sorted(maps.Keys(w.Header())) {
fmt.Printf(" %s: %s\n", k, strings.Join(w.Header()[k], ", "))
}
}
func main() {
do("OPTIONS", "https://app.example.com", map[string]string{
"Access-Control-Request-Method": "PUT",
"Access-Control-Request-Headers": "authorization, content-type",
})
do("GET", "https://app.example.com", nil)
do("GET", "https://evil.example", nil)
}
OPTIONS from "https://app.example.com" -> 204
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Expose-Headers: X-Request-Id
Access-Control-Max-Age: 600
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
GET from "https://app.example.com" -> 200
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Expose-Headers: X-Request-Id
Content-Type: text/plain; charset=utf-8
Vary: Origin
X-Request-Id: req-42
GET from "https://evil.example" -> 200
Content-Type: text/plain; charset=utf-8
Vary: Origin
X-Request-Id: req-42
Important details:
- echo back a specific allowed origin.
Access-Control-Allow-Origin: *is fine for public data, but browsers refuse to send cookies or credentials with it - add
Vary: Originbecause the response differs per origin, otherwise a shared cache may serve one origin's response to another Access-Control-Expose-Headerslists response headers JavaScript is allowed to read, beyond a few basic ones likeContent-Type- CORS is enforced by browsers only. It doesn't protect your API from other clients like
curl
For middleware in general, see HTTP server middleware.
Client IP behind a proxy
Behind a load balancer or reverse proxy, r.RemoteAddr is the address of the proxy. Proxies add the original client address to X-Forwarded-For (or the standardized Forwarded header).
Any client can send its own X-Forwarded-For, so never trust it blindly. Only look at it when the connection comes from a proxy you control, and read it from the right, skipping your own proxies:
package main
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
)
// proxies we run ourselves, e.g. a load balancer
var trustedProxies = []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}
func isTrusted(a netip.Addr) bool {
for _, p := range trustedProxies {
if p.Contains(a) {
return true
}
}
return false
}
// clientIP walks X-Forwarded-For from the right, skipping trusted proxies.
// The leftmost entries are supplied by the client and can be forged.
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return ""
}
addr, err := netip.ParseAddr(host)
if err != nil || !isTrusted(addr) {
return host // direct connection: ignore X-Forwarded-For
}
var hops []string
for _, v := range r.Header.Values("X-Forwarded-For") {
hops = append(hops, strings.Split(v, ",")...)
}
for i := len(hops) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
if err != nil {
break
}
if !isTrusted(a) {
return a.String()
}
}
return host
}
func main() {
tests := []struct{ remote, xff string }{
{"203.0.113.7:51000", ""},
{"203.0.113.7:51000", "1.2.3.4"}, // client forging the header
{"10.0.0.5:40000", "198.51.100.23"}, // via our load balancer
{"10.0.0.5:40000", "1.2.3.4, 198.51.100.23"}, // forged value + real one
{"10.0.0.5:40000", "198.51.100.23, 10.0.0.9"}, // two of our proxies
}
for _, tc := range tests {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = tc.remote
if tc.xff != "" {
r.Header.Set("X-Forwarded-For", tc.xff)
}
fmt.Printf("%-18s %-26q -> %s\n", tc.remote, tc.xff, clientIP(r))
}
}
203.0.113.7:51000 "" -> 203.0.113.7
203.0.113.7:51000 "1.2.3.4" -> 203.0.113.7
10.0.0.5:40000 "198.51.100.23" -> 198.51.100.23
10.0.0.5:40000 "1.2.3.4, 198.51.100.23" -> 198.51.100.23
10.0.0.5:40000 "198.51.100.23, 10.0.0.9" -> 198.51.100.23
If you use httputil.ReverseProxy in the other direction, it adds X-Forwarded-For for you. Its Rewrite hook with r.SetXForwarded() sets X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto together.
Limits and invalid values
Headers are attacker-controlled input. net/http protects you in a few ways:
package main
import (
"errors"
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strings"
)
func main() {
srv := httptest.NewUnstartedServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// a value containing a newline would let an attacker inject headers
name := r.URL.Query().Get("name")
w.Header().Set("X-Name", name)
fmt.Fprintln(w, "ok")
}))
srv.Config.MaxHeaderBytes = 4 << 10 // 4 KB instead of the default 1 MB
srv.Start()
defer srv.Close()
// 1. request headers too large
req, _ := http.NewRequest("GET", srv.URL, nil)
req.Header.Set("X-Big", strings.Repeat("a", 10_000))
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println("big header:", resp.Status)
// 2. the client refuses to send invalid header values
req, _ = http.NewRequest("GET", srv.URL, nil)
req.Header.Set("X-Evil", "a\r\nX-Injected: 1")
_, err = http.DefaultClient.Do(req)
var uerr *url.Error
if errors.As(err, &uerr) {
fmt.Println("client:", uerr.Err)
}
// 3. the server drops response headers with invalid values
resp, err = http.Get(srv.URL + "?name=bob%0d%0aSet-Cookie:%20admin=1")
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println("server:", resp.Status)
fmt.Printf("X-Name: %q\n", resp.Header.Get("X-Name"))
fmt.Printf("Set-Cookie: %q\n", resp.Header.Get("Set-Cookie"))
}
big header: 431 Request Header Fields Too Large
client: net/http: invalid header field value for "X-Evil"
server: 200 OK
X-Name: "bob Set-Cookie: admin=1"
Set-Cookie: ""
http.Server.MaxHeaderByteslimits the size of request headers. The default is 1 MB (http.DefaultMaxHeaderBytes). Larger requests get431 Request Header Fields Too Large- the client refuses to send a header value containing
\ror\n - the server replaces
\rand\nin response header values with spaces, so a value copied from user input can't inject aSet-Cookieheader. You should still validate such values instead of relying on this
For more on hardening a server, including security headers like Content-Security-Policy and Strict-Transport-Security, see Application security.
Debugging: dump the raw request
When an API rejects your request, it helps to see exactly what's sent. httputil.DumpRequestOut shows the request in wire format, including the headers the transport adds:
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"strings"
)
func main() {
body := strings.NewReader(`{"name":"widget"}`)
req, err := http.NewRequest("POST", "https://api.example.com/items?draft=1", body)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer abc")
// DumpRequestOut shows the request as the client would send it,
// including headers added by the transport
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Fatal(err)
}
fmt.Print(strings.ReplaceAll(string(dump), "\r\n", "\n"))
}
POST /items?draft=1 HTTP/1.1
Host: api.example.com
User-Agent: Go-http-client/1.1
Content-Length: 17
Authorization: Bearer abc
Content-Type: application/json
Accept-Encoding: gzip
{"name":"widget"}
On the server, httputil.DumpRequest(r, false) does the same for an incoming request, and httputil.DumpResponse for a response.
Summary
http.Headeris amap[string][]stringwith canonical keys; useGet,Set,Add,ValuesandDelrather than indexing the mapHostlives inr.Host/req.Host, not in the header map- set response headers before
WriteHeaderor the firstWrite - always set
Content-Typeexplicitly - use
mime.ParseMediaType,http.ParseTimeandr.BasicAuthto parse structured values - let
http.ServeContenthandleETag,If-None-Match,If-Modified-SinceandRange - wrap
http.RoundTripperto add headers to every client request - never trust
X-Forwarded-Forfrom connections that don't come from your own proxies