Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go HTTP Post and use Cookies

I'm trying to use Go to log into a website and store the cookies for later use.

Could you give example code for posting a form, storing the cookies, and accessing another page using the cookies?

I think I might need to make a Client to store the cookies, by studying http://gotour.golang.org/src/pkg/net/http/client.go

package main  import ("net/http"         "log"         "net/url"         )  func Login(user, password string) string {         postUrl := "http://www.pge.com/eum/login"          // Set up Login         values := make(url.Values)         values.Set("user", user)         values.Set("password", password)          // Submit form         resp, err := http.PostForm(postUrl, values)         if err != nil {                 log.Fatal(err)         }         defer resp.Body.Close()          // How do I store cookies?         return "Hello" }  func ViewBill(url string, cookies) string {  //What do I put here?  } 
like image 431
Lionel Avatar asked Oct 06 '12 04:10

Lionel


People also ask

Can we set-cookie in post request?

After receiving an HTTP request, a server can send one or more Set-Cookie headers with the response. The browser usually stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header.

How do I add cookies to my HTTP request?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

Does HTTP request contain cookies?

The Cookie HTTP request header contains stored HTTP cookies associated with the server (i.e. previously sent by the server with the Set-Cookie header or set in JavaScript using Document. cookie ). The Cookie header is optional and may be omitted if, for example, the browser's privacy settings block cookies.

How do I send a post request in go?

Go HTTP POST request FORM data The Content-Type header is set to application/x-www-form-urlencoded. The data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. We send a POST request to the https://httpbin.org/post page.


1 Answers

Go 1.1 introduced a cookie jar implementation net/http/cookiejar.

import (     "net/http"     "net/http/cookiejar" )  jar, err := cookiejar.New(nil) if err != nil { // error handling }  client := &http.Client{     Jar: jar, } 
like image 178
greenimpala Avatar answered Sep 28 '22 20:09

greenimpala