Golang transform http.Header into array

huangapple go评论82阅读模式
英文:

Golang transform http.Header into array

问题

我正在发送POST请求:

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

我以http.Header类型的格式接收resp.Header

我需要像这样的结果:

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

我不知道如何解决这个问题,因为我不知道如何处理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

答案1

得分: 9

resp.Header 是类型为 http.Header 的变量。你可以在文档中看到,这个类型也是一个 map,因此你可以用两种不同的方式访问它:

  1. 使用 http.Header 的方法:

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

如果存在该头部信息,你将得到它的第一个值(请记住,一个头部名称可能有多个值);否则你将得到一个空字符串。

  1. 使用 map 的方法:

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

如果存在该头部信息,ok 将为 true(即头部信息 存在),你将得到一个包含该头部所有值的字符串切片;否则,ok 将为 false(即头部信息 不存在)。

使用你喜欢的任何一种方法。

如果你需要遍历所有的头部值,你可以这样做:

for name, value := range resp.Header() {
    fmt.Printf("%v: %v\n", name, value)
}
英文:

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.

  1. 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)
}

答案2

得分: 8

你可以使用以下这个函数:

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
}

它会返回一个符合你要求的数组。

英文:

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.

答案3

得分: 1

这个解决方案适用于 go version go1.13 windows/amd64

http.Request 中的请求对象包含 Header 对象。我们在这里使用的是 net/http 包。您可以使用以下方法按名称获取所有标头的值:

import (
	"net/http"
)

type RequestHeaders struct {
	ContentType   string `json:"content-type"`
	Authorization string `json:"authorization"`
}

func getHeaders(r *http.Request) RequestHeaders {
	contentType := r.Header.Get("Content-Type")
	authorization := r.Header.Get("Authorization")
	headers := RequestHeaders{
		ContentType:   contentType,
		Authorization: authorization,
	}
	return headers
}

您可以看到,我们使用 r.Header.Get("Content-Type") 方法来获取标头的值。

如果标头缺失,Get() 方法将返回空字符串。

英文:

This solutions is for go version go1.13 windows/amd64.

The request object from http.Request contains Header object. We are using net/http package here. You can get values of all headers by name using following method:

import(
	"net/http"
)

type RequestHeaders struct {
	ContentType      string      `json: "content-type"`
	Authorization    string      `json: "authorization"`
}

func getHeaders(r *http.Request) RequestHeaders {
		contentType := r.Header.Get("Content-Type")
		authorization := r.Header.Get("Authorization")
		headers := RequestHeaders{
						Content-Type: contentType,
						Authorization: authorization}
		return headers
}

You can see that we are using r.Header.Get("Content-Type") method to get value of the header.

If the header is missing the Get() method will return empty string.

答案4

得分: 0

你可以使用resp.Header().Get()方法来获取响应头的第一个值,如果头部键没有值,则返回""

因此,在你的情况下,可以这样写:

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

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")

huangapple
  • 本文由 发表于 2016年3月1日 07:23:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/35711767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定