Lucas Beier
Lucas Beier

Reputation: 631

Golang http.PostParam not showing all Cookies in the Response

I'm studying Golang and I'm trying to reach an endpoint (which I don't have control).

That's the code I wrote:

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

The Println prints [PHPSESSID=<ID>; Path=/; HttpOnly].

When doing the same request in 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>

I can see two cookies being set in the response, the PHPSESSID (which I guess is the same in Golang) and au (which is the token I need in order to authenticate against the server).

I'm not sure what I'm doing wrong and why I cannot see the au Cookie when calling the endpoint using the Golang code.

Any guess?

Upvotes: 1

Views: 636

Answers (1)

You probably have an HTTP redirection (302 or 301).

Try this:

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())
}

In the overview of the net/http package documentation you have an example on how to control the redirection policy.

Good luck.

Upvotes: 1

Related Questions