Home > Net >  How to get a single cookie by name from response.Cookies() in Golang?
How to get a single cookie by name from response.Cookies() in Golang?

Time:04-20

Is there a way how to get only one cookie by name from response.Cookies()?

Let's say that I need the wr_entry_path cookie from this cookie jar down below. [wr_entry_path=/aP3Mk1i6M/xcp0g1/vMg/Qpr7ccN0OE3p/YxU3A31SAw/RWoGdE/k2DyQ; Path=/; Expires=Tue, 19 Apr 2022 19:40:03 GMT waitingroom=1650392103~id=072e61d9e7fa58639a6a2af28cea89de; Path=/; HttpOnly; Secure; SameSite=None]

Any help appreciated!!

CodePudding user response:

Response.Cookies() returns you a slice of all parsed http.Cookies. Simply use a loop to iterate over it and find the one that has the name you're looking for:

cookies := resp.Cookies()
for _, c := range cookies {
    if c.Name == "wr_entry_path" {
        // Found! Use it!
        fmt.Println(c.Value) // The cookie's value
    }
}
  • Related