将未更改的小写标头添加到golang http请求
I am trying to set all-lowercase headers in a golang program and CanonicalMIMEHeaderKey is uppercasing the first letter. The API I am consuming only takes this particular header in all-lowercase at the moment. It's not an option to change that at this point in time. Is there a way to override that?
http://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey
So for example, the header I want to add is:
req.Header.Add("myheader", "myheadervalue")
But it comes out as:
req.Header.Add("Myheader", "myheadervalue")
Can anyone help please?
Thanks
我正在尝试在golang程序中设置全部小写的标头,而CanonicalMIMEHeaderKey将大写的首字母大写。 我正在使用的API目前仅以小写形式使用此特定标头。 目前无法更改此选项。 有没有办法覆盖它? p>
http://golang.org/pkg/net / textproto /#CanonicalMIMEHeaderKey p>
例如,我要添加的标题为: p>
req.Header。 Add(“ myheader”,“ myheadervalue”)
code> pre>
但是它显示为: p>
req.Header .Add(“ Myheader”,“ myheadervalue”)
code> pre>
有人可以帮忙吗? p>
谢谢 p> \ n div>
I do not see a way to circumvent this but if you really have to use lower-case header names, then you can work around this by creating your own http.Header
with lower-case keys. Example (on play):
import "fmt"
import "strings"
import "net/http"
// ...
req, _ := http.NewRequest("GET", "http://foo", nil)
req.Header.Add("myheader", "myheadervalue")
lowerCaseHeader := make(http.Header)
for key, value := range req.Header {
lowerCaseHeader[strings.ToLower(key)] = value
}
req.Header = lowerCaseHeader
I ran into a similar problem and solved it a slightly different way that I thought might be helpful for others coming to this post in the future...
Since http.Header is just a map[string][]string
under the hood, you can create an http.Header then assign it to the request's header. Because this does not use the Add nor the Set method, this will preserve casing.
Like so:
import "net/http"
// ...
headers := http.Header{
"my-lowercase-header": []string{"myvalue1"},
"Accept": []string{"text/plain", "text/html"},
}
client := &http.Client{}
req, err := http.NewRequest("GET", "http://www.example.com", nil)
if err != nil {
panic(err)
}
req.Header = headers
resp, err := client.Do(req)
There is another easy way.
req.Header["myheader] = []string{"myheadervalue"}