无法通过 net/http 调用获取整个 header 元素

Can't fetch whole the header element via net/http call

我想获得一个名为 Set-Cookie 的 header 元素,它位于身份验证服务的响应中。

我进行 http 调用以从远程服务器获取数据:

resp, err := client.Do(httpRequest)

登录后,响应如下:

fmt.Println(resp.Header)
// the result is:
// map[Cache-Control:[private] Content-Length:[0] Content-Security-Policy:[frame-ancestors 'self'] Date:[Tue, 01 Sep 2020 06:44:02 GMT] Expires:[0] Pragma:[no-cache] Set-Cookie:[sg-dummy=-; path=/; HttpOnly sg-auth-XXXX=4a49891d-2c46-4f50-a516-68a2e337f2a7; path=/; HttpOnly] X-Frame-Options:[SAMEORIGIN] X-Xss-Protection:[1; mode=block]]

我想要这个元素:

Set-Cookie:[sg-dummy=-; path=/; HttpOnly sg-auth-XXXX=4a49891d-2c46-4f50-a516-68a2e337f2a7; path=/; HttpOnly]

但是,一旦我得到那部分,我就会看到 Set-Cookie 字符串的编辑版本:

fmt.Println(resp.Header.Get("Set-Cookie")
// I get this part only:
// sg-dummy=-; path=/; HttpOnly

我应该如何获得所有东西?

Headers 可以有多个与给定键相关联的值。你的例子就是这种情况。

Header.Get returns 仅与给定键关联的第一个值:

Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "".

相反,您需要使用 Header.Values 其中 returns 所有这些:

Values returns all values associated with the given key.

fmt.Println(resp.Header.Values("Set-Cookie"))

我建议阅读您使用的函数的文档。

似乎有多个 cookie。如果 header 有多个元素,Header.Get 只会 return 第一个元素。将其作为地图访问:

for _,cookie:=range resp.Header["Set-Cookie"] {
   // This should iterate twice
}