Go get me some cookies
Introduction:
There isnt really much to intro with this post , I am simply going to demonstrate how to use cookies with Go’s net/http lib.
This in itself is super easy (unless you are a noob like me).
Onto the code :
package main
import (
"net/http"
"net/url"
"net/http/cookiejar"
)
func main(){
jar,_ := cookiejar.New(nil)
client := &http.Client{Jar:jar}
client.Get("http://google.com")
formData := url.Values{"username": {"myUsername"}, "password": {"myPassword"} }
client.PostForm("http://google.com/login", formData)
}
First of the imports used are under the assumption that you are posting to some service as if you were logging in. If you do not need this then you can kill line 5 and anything url related.
The first import is the standard net/http for making requests , next is the net/url import which is used as a easy way to represent form values when they need to be submitted. Lastly is the net/http/cookiejar which contains the implementation of a cookiejar which will be used to store our session cookies while making requests.
On line 10 create a new instance of the cookiejar passing in no options as this will get you started 99% of the time. Once we have a new cookiejar object we pass that as a parameter to a new instance of the http.Client.
Under normal circumstances requests such as GET/POST etc will be made directly with the http.Get helper method. But because we want to resuse the cookies between requests we need to create an instance of the underlying http.Client object.
Thats all there is to it really , in summary create a cookiejar and ensure you use the same http.Client object for all your requests.