Golang将http.Header转换为数组

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

You can retrieve the response header's first value with resp.Header().Get(), which returns "" if the header key has no values.

Hence, in your case

var a [2]string
a[0] = resp.Header().Get("server")
a[1] = resp.Header().Get("date")

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
", name, value)
}

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.