Iterating HTTP client response headers in Go

In this example we iterate all the HTTP headers the server sends back after a HTTP request made with theĀ net/http Go library.

for name, headers := range resp.Header {
    // Iterate all headers with one name (e.g. Content-Type)
    for _, hdr := range headers {
        println(name + ": " + hdr)
    }
}

Full example:

package main

import (
    "net/http"
)

func main() {
    // Perform request
    resp, err := http.Get("https://ipv4.techoverflow.net/api/get-my-ip")
    if err != nil {
        print(err)
        return
    }
    // Cleanup when this function ends
    defer resp.Body.Close()
    // Read all the headers
    for name, headers := range resp.Header {
        // Iterate all headers with one name (e.g. Content-Type)
        for _, hdr := range headers {
            println(name + ": " + hdr)
        }
    }
}

This example will print, for example:

Content-Type: application/octet-stream
Content-Type: text/plain charset=UTF-8
Content-Length: 11
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
Server: nginx/1.14.0 (Ubuntu)
Date: Sat, 16 Nov 2019 00:27:05 GMT