Skip to content

Instantly share code, notes, and snippets.

@andelf
Last active Jun 20, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@boarpig 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?

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Mar 26, 2013

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

@0x4139

This comment has been minimized.

Copy link

@0x4139 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