Skip to content

Instantly share code, notes, and snippets.

@andelf
Last active June 20, 2017 05:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andelf/2216371 to your computer and use it in GitHub Desktop.
Save andelf/2216371 to your computer and use it in GitHub Desktop.
A golang in memory cookiejar
// MIT license (c) andelf 2012
type InMemoryCookieJar struct{
storage map[string][]http.Cookie
}
// buggy... but works
func (jar InMemoryCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
for _, ck := range cookies {
path := ck.Domain
if ck.Path != "/" {
path = ck.Domain + ck.Path
}
if ck.Domain[0] == '.' {
path = path[1:] // FIXME: .hi.baidu.com won't match hi.baidu.com
}
if _, found := jar.storage[path]; found {
setted := false
for i, v := range jar.storage[path] {
if v.Name == ck.Name {
jar.storage[path][i] = *ck
setted = true
break
}
}
if ! setted {
jar.storage[path] = append(jar.storage[path], *ck)
}
} else {
jar.storage[path] = []http.Cookie{*ck}
}
}
}
func (jar InMemoryCookieJar) Cookies(u *url.URL) []*http.Cookie {
cks := []*http.Cookie{}
log.Println("get cookies", u)
for pattern, cookies := range jar.storage {
if strings.Contains(u.String(), pattern) {
for i := range cookies {
cks = append(cks, &cookies[i])
log.Println("add cookie", cookies[i].Name)
}
}
}
return cks
}
func newCookieJar() InMemoryCookieJar {
storage := make(map[string][]http.Cookie)
return InMemoryCookieJar{storage}
}
// use:
// client := &http.Client{Jar: newCookieJar()}
@boarpig
Copy link

boarpig commented Jan 11, 2013

Can you define a license for this? Then again, I would probably get pretty close to identical implementation if I did it myself, so does the license matter?

Copy link

ghost commented Mar 26, 2013

Implementations of CookieJar must be safe for concurrent use by multiple goroutines

@0x4139
Copy link

0x4139 commented Oct 21, 2015

you need some mutex locks

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