Skip to content

Instantly share code, notes, and snippets.

@yeknava
Last active December 27, 2021 00:22
Show Gist options
  • Save yeknava/cde608416899a9070155 to your computer and use it in GitHub Desktop.
Save yeknava/cde608416899a9070155 to your computer and use it in GitHub Desktop.
Golang get cookie by name
func getCookieByName(cookie []*http.Cookie, name string) string {
cookieLen := len(cookie)
result := ""
for i := 0; i < cookieLen; i++ {
if cookie[i].Name == name {
result = cookie[i].Value
}
}
return result
}
@gghez
Copy link

gghez commented Nov 25, 2018

I would add break after first found (line 7).

@460s
Copy link

460s commented Aug 19, 2020

I think it's better to take a value without a loop.
From request. r.Cookie("name")

// Cookie returns the named cookie provided in the request or
// ErrNoCookie if not found.

@yeknava
Copy link
Author

yeknava commented Aug 19, 2020

I think it's better to take a value without a loop.
From request. r.Cookie("name")

// Cookie returns the named cookie provided in the request or
// ErrNoCookie if not found.

its pretty old code. thanks for mentioning that method

@alielbashir
Copy link

Thanks @460s , was looking for this everywhere

@veilm
Copy link

veilm commented Dec 27, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment