如果使用Header().Set()方法,HTTP响应头字段会自动将首字母和“-”后的第一个字母转换为大写,其余转换为小写,如 "accept-encoding" 转换为 "Accept-Encoding"。这个转换规则在绝大多数情况是没有问题的,但是有些字段如“P3P”,按约定应该是全大写的,如果转成“P3p”,可能会引起前端异常。如果想要控制字母的大小写,官方文档提供了一种解决办法就是直接操作Header哈希表(map[string][]string),“To use non-canonical keys, assign to the map directly.”,示例如下:
func handleFunc(urlstr string, handler Handler) {
f := func(w http.ResponseWriter, r *http.Request) {
//logger.Info(r.URL.RequestURI())
w.Header().Set("Cache-Control", "no-cache, no-store")
header := w.Header()
header["P3P"] = []string{"CP=\"NOI DEV PSA PSD IVA PVD OTP OUR OTR IND OTC\""}
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Connection", "keep-alive")
handler.Run(w, r)
}
http.HandleFunc(urlstr, f)
}
响应头如下:
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Connection: keep-alive
Content-Type: text/plain
P3P: CP="NOI DEV PSA PSD IVA PVD OTP OUR OTR IND OTC"
Pragma: no-cache
Date: Fri, 30 Apr 2021 01:54:55 GMT
Content-Length: 0