如何在使用Golang时在请求头中保持键的大小写敏感?

huangapple go评论85阅读模式
英文:

how to keep key case sensitive in request header using golang?

问题

我最近在使用Go语言的"net/http"库,在向请求添加一些头信息时,发现头部键名发生了变化,例如:

request, _ := http.NewRequest("GET", fakeurl, nil)
request.Header.Add("MyKey", "MyValue")
request.Header.Add("MYKEY2", "MyNewValue")
request.Header.Add("DONT-CHANGE-ME", "No")

然而,当我获取HTTP消息包时,发现头部键名变成了这样:

Mykey: MyValue
Mykey2: MyNewValue
Dont-Change-Me: No

我使用的是Go 1.3版本,请问如何保持键名的大小写敏感或保持其原始样式?谢谢。

英文:

I am recently using golang library "net/http",while add some header info to request, I found that the header keys are changing, e.g

request, _ := &http.NewRequest("GET", fakeurl, nil)
request.Header.Add("MyKey", "MyValue")
request.Header.Add("MYKEY2", "MyNewValue")
request.Header.Add("DONT-CHANGE-ME","No")

however, when I fetch the http message package, I found the header key changed like this:

Mykey: MyValue
Mykey2: MyNewValue
Dont-Change-Me:  No

I using golang 1.3, then how to keep key case sensitive or keep its origin looking?
thx.

答案1

得分: 20

http.HeaderAddSet 方法在向头部映射添加值时会规范化头部名称。你可以通过使用映射操作绕过规范化:

request.Header["MyKey"] = []string{"MyValue"}
request.Header["MYKEY2"] = []string{"MyNewValue"}
request.Header["DONT-CHANGE-ME"] = []string{"No"}

只要你对传输中已知的头部使用规范名称,这样就可以工作。

英文:

The http.Header Add and Set methods canonicalize the header name when adding values to the header map. You can sneak around the canonicalization by adding values using map operations:

request.Header["MyKey"] = []string{"MyValue"}
request.Header["MYKEY2"] = []string{"MyNewValue"}
request.Header["DONT-CHANGE-ME"] = []string{"No"}

As long as you use canonical names for headers known to the transport, this should work.

huangapple
  • 本文由 发表于 2014年10月14日 10:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/26351716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定