Get HTTP Response Headers in Go

Published: April 27, 2020

Tags:

The Theory and Practice blog has a nice example of accessing HTTP Response Headers in Go.

The example provided shows how we can a loop through the Header map and print each key and value. One thing that wasn’t immediately clear to me was the best way to access a specific header, without the loop.

I did a bit of research and found the Get function was helpful here.

Here’s an example of accessing the Content-Security-Policy header:

resp, err := http.Get(url)
if err != nil {
    log.Fatal(err)
}

fmt.Println(resp.Header.Get("Content-Security-Policy"))

It’s worth noting that Header is actually the following type:

map[string][]string

This is because a server can issue the same response header multiple times. In this case, Get will return the first value.

The entire slice of values can be accessed directly by key:

values := resp.Header["Content-Security-Policy"]

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but loves dabbling in other languages like Go and Ruby. Technical topics that interest me are monitoring, security and performance. I'm also a stickler for good documentation and clear technical writing.

During the day I lead a team of developers and solve challenging technical problems at Rightpoint where I mainly work with the Magento platform. I've also spoken at a number of events.

In my spare time I blog about tech, work on open source and participate in bug bounty programs.

If you'd like to get in contact, you can find me on Twitter and LinkedIn.