Canonical Keys In http.Header

http.Header canonicalizes keys on Set and matches them case-insensitively on Get, while Add stacks multiple values under one header name.

GoData Fetching

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"net/http"
	"net/textproto"
)

func main() {
	h := http.Header{}

	// Set 规范化键名:x-request-id 实际存成 X-Request-Id
	h.Set("x-request-id", "abc-123")
	fmt.Println("canonical form:", textproto.CanonicalMIMEHeaderKey("x-request-id"))

	// Get 对大小写不敏感:查找前先规范化
	fmt.Println("get ignores case:", h.Get("X-REQUEST-ID") == h.Get("x-request-id"))

	// Add 在同名键下追加多值:Set-Cookie 天然是多值头
	h.Add("Set-Cookie", "a=1")
	h.Add("Set-Cookie", "b=2")
	fmt.Println("all values:", h.Values("Set-Cookie"))
	fmt.Println("first value:", h.Get("Set-Cookie"))

	// Del 一次清掉该键下的全部值
	h.Del("Set-Cookie")
	fmt.Println("after del:", h.Values("Set-Cookie"))
}

The actions behind the output

Count the function main as the entire surface area of Canonical Keys In http.Header.

Using it

Running the file prints labeled results such as canonical form:, get ignores case:, all values: — each operation’s effect is visible in the output.

Key statements

h.Set("x-request-id", "abc-123")

Interactive Tools for This Topic

FAQ

What does Canonical Keys In http.Header print when run?
No setup needed: run the file and look for labeled lines like `canonical form:`, `get ignores case:`, `all values:` in the output.