英文:
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.Header 的 Add 和 Set 方法在向头部映射添加值时会规范化头部名称。你可以通过使用映射操作绕过规范化:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论