Fetching site cookies via Go
Depicts the usage of cookiejar to retrieve cookies from a website.
type MyClient struct {
client http.Client //http client
jar *cookiejar.Jar //jar
}
// init - initialises the http client
func (s *MyClient) init() {
s.jar, _ = cookiejar.New(nil)
s.client = http.Client{Jar: s.jar}
}
// getCookies - Gets cookies
func (s *MyClient) getCookies() map[string][]*http.Cookie {
cookies := make(map[string][]*http.Cookie)
r, err := s.client.Get("https://some-website.com")
if err != nil {
fmt.Println(err)
return cookies
}
defer r.Body.Close()
siteCookies := s.jar.Cookies(r.Request.URL)
cookies["cookies"] = siteCookies
return cookies
}
func main() {
cc := &MyClient{}
cc.init()
cookies := cc.getCookies()
fmt.Println(cookies)
}