Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get cookie from Golang post

Tags:

ruby

go

How do I send the post in GoLang?

I have the following code in ruby, now I need to transfer into Golang.

http = Net::HTTP.new('example.com', 443)
http.use_ssl = true
http

path = '/abc/login'
data = 'data[Account][username]=myusername&data[Account][passwd]=mypassword'
resp, _ = http.post(path, data)

This way, I can get the cookie after login request.

But I don't know how to send a post request in Go.

I've written the following code.

path := "https://example.com/abc/login"
data := strings.NewReader("data[Account][username]=myusername&data[Account][passwd]=mypassword")
resp, err := http.Post(path, "text/html; charset=UTF-8", data)

It seems not correct, because I didn't find a way to get cookie.

like image 848
Coda Chang Avatar asked May 23 '18 08:05

Coda Chang


2 Answers

//Create Client

client=http.client{}

//Create Varible

var cookie []*http.Cookie

// Create Request

req, _ := http.NewRequest("GET", url, nil)
resp, err := client.Do(req) //send request
if err != nil {
return 
}
cookie = resp.Cookies() //save cookies

// Create New Request

req, _ := http.NewRequest("POST", url, nil)   
for i := range cookie {
    req.AddCookie(cookie[i])
}
resp, err := client.Do(req) //send request
if err != nil {
      return 
              }
like image 199
Muhammed Sertkaya Avatar answered Nov 15 '22 12:11

Muhammed Sertkaya


To get the cookies you should call the Cookies() method that's part of http.Response, try this:

for _, cookie := range resp.Cookies() {
  fmt.Println("Found a cookie named:", cookie.Name)
}

See the Cookie fields here.

like image 17
Matías Insaurralde Avatar answered Nov 15 '22 11:11

Matías Insaurralde