Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang transform http.Header into array

Tags:

go

I'm sending POST request:

req, err := http.NewRequest("POST", link, bytes.NewBuffer(jsonStr))
client := &http.Client{Timeout: tm}
resp, err := client.Do(req)

I receive resp.Header in format with type http.Header

I need to something like this:

[
    "Server: nginx/1.4.4",
    "Date: Wed, 24 Feb 2016 19:09:49 GMT"
]

I don't know how to approach this problem, because I don't know how to deal with http.Header datatype. Could someone help please

like image 884
Jess J Avatar asked Feb 29 '16 23:02

Jess J


2 Answers

resp.Header is of type http.Header. You can see in the documentation that this type is also a map, so you can access it in two different ways:

1) By using http.Header's methods:

serverValue := resp.Header().Get("Server")
dataValue := resp.Header().Get("Date")

If the header exists, you'll get its first value (keep in mind that there might be multiple values for a single header name); otherwise you'll get an empty string.

2) By using map's methods:

serverValue, ok := resp.Header()["Server"]
dataValue, ok := resp.Header()["Date"]

If the header exists, ok will be true (i.e. the header exists) and you'll get a slice of strings containing all the values for that header; otherwise, ok will be false (i.e. the header doesn't exist).

Use whichever method you prefer.

If you need to iterate over all the header values, you can do it with something like:

for name, value := range resp.Header() {
    fmt.Printf("%v: %v\n", name, value)
}
like image 133
cd1 Avatar answered Oct 01 '22 16:10

cd1


You could use a function like this one:

func HeaderToArray(header http.Header) (res []string) {
    for name, values := range header {
        for _, value := range values {
            res = append(res, fmt.Sprintf("%s: %s", name, value))
        }
    }
    return
}

It should return an array like the one you want.

like image 20
Juan Cespedes Avatar answered Oct 01 '22 16:10

Juan Cespedes