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? }
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.
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.
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.
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.
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, }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With