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 also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.