Search code examples
gorequestsession-cookiesgo-http

How to maintain the same session using a cookie jar in Go


I am wondering how I can maintain the same session using a cookie jar in Go

I have done this in JS using this method:

const cookieJar = request.jar();

request({
    headers: {
    //headers here
    },
    url: url,
    jar: cookieJar
    method: 'GET'

I am wondering if there is an euqivalent of the above code for Go. Thanks!


Solution

  • You cat try something like this:

    req, err := http.NewRequest("GET", "http://localhost:8080/", nil)
    if err != nil { // ... }
    
    jar, err := cookiejar.New(nil)
    if err != nil { // ... }
    
    client := &http.Client{Jar: jar}
    
    res, err := client.Do(req)
    if err != nil { // ... }