http - Golang http.PostParam 未在响应中显示所有 Cookie

标签 http go

我正在研究 Golang,我正试图达到一个终点(我无法控制)。

这是我写的代码:

params := url.Values{}
params.Add("data[User][username]", <THE_USERNAME>)
params.Add("data[User][password]", <THE_PASSWORD>)
resp, _ := http.PostForm(<LOGIN_URL>, params)

fmt.Println(resp.Cookies())

Println版画 [PHPSESSID=<ID>; Path=/; HttpOnly] .

在 Postman 中做同样的请求时

POST /login HTTP/1.1
Host: <HOST>
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 399a42af-00f2-4340-b7fa-1ae1fa295b62

<PARAM_DATA>

我可以看到响应中设置了两个 cookie,PHPSESSID (我猜这在 Golang 中是一样的)和 au (这是我需要的 token ,以便针对服务器进行身份验证)。

我不确定我做错了什么以及为什么我看不到 au使用 Golang 代码调用端点时的 Cookie。

有什么猜测吗?

最佳答案

您可能有 HTTP 重定向(302 或 301)。

试试这个:

package main

import (
    "log"
    "net/http"
    "net/url"
)

func main() {
    params := url.Values{}
    params.Add("data[User][username]", "test")
    params.Add("data[User][password]", "test")

    client := &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    resp, err := client.PostForm("http://example.com", params)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(resp.Cookies())
}

在 net/http 包的概述中 documentation你有一个关于如何控制重定向策略的例子。

祝你好运。

关于http - Golang http.PostParam 未在响应中显示所有 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528092/

相关文章:

pointers - Golang返回指向接口(interface)的指针抛出错误

go - 尝试在go中创建可重用的追加到struct

java - 在服务器上运行 struts2 应用程序时出现 http 状态 404

python - 支持智能流水线/多路复用的代理服务器

http - 使用 PL/SQL HTTP 上传 BLOB 文件

ios - PCL 中的 HttpClient 调用在 iOS 中不起作用

mysql - 为什么这一小段代码需要 11 秒来执行这几个数据库调用?

go - 使用底层类型制作接口(interface){}参数的副本

javascript - Node .js `request.get` : store body in variable

go - Netlify 函数 (AWS Lambda) 示例 "hello"Golang 函数 : Invalid or unexpected token