http-postgocookiejar

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?

}

Solution

  • 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,
    }