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?
}
Another way of doing it. Works in Go 1.8.
At the version 1.5 of Go, we can use http.NewRequest to make a post request with cookie.
Go 1.1 introduced a cookie jar implementation
net/http/cookiejar
.First you'll need to implement the
http.CookieJar
interface. You can then pass this into the client you create and it will be used for requests made with the client. As a basic example: