Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add unaltered lowercase headers to golang http request

Tags:

go

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

like image 359
egreene Avatar asked Oct 21 '25 23:10

egreene


1 Answers

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
like image 186
nemo Avatar answered Oct 24 '25 15:10

nemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!