File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ package httputil
2+
3+ import (
4+ "net/http"
5+ "net/http/cookiejar"
6+ "net/url"
7+ "sync"
8+ )
9+
10+ // Option represents a configuration option for the cookie jar
11+ type Option func (* CookieJar )
12+
13+ // WithCookieJar sets an existing cookie jar to wrap
14+ func WithCookieJar (jar http.CookieJar ) Option {
15+ return func (cj * CookieJar ) {
16+ cj .jar = jar
17+ }
18+ }
19+
20+ // CookieJar is a thread-safe wrapper around http.CookieJar
21+ type CookieJar struct {
22+ jar http.CookieJar
23+ mu sync.RWMutex
24+ }
25+
26+ // New creates a new thread-safe cookie jar with the given options
27+ // If no jar is provided, creates a simple in-memory cookie jar
28+ func NewCookieJar (opts ... Option ) (* CookieJar , error ) {
29+ cj := & CookieJar {}
30+
31+ // Apply options
32+ for _ , opt := range opts {
33+ opt (cj )
34+ }
35+
36+ // If no jar was provided, create a new one
37+ if cj .jar == nil {
38+ jar , err := cookiejar .New (nil )
39+ if err != nil {
40+ return nil , err
41+ }
42+ cj .jar = jar
43+ }
44+
45+ return cj , nil
46+ }
47+
48+ // SetCookies implements http.CookieJar.SetCookies
49+ func (cj * CookieJar ) SetCookies (u * url.URL , cookies []* http.Cookie ) {
50+ if cj .jar == nil {
51+ return
52+ }
53+
54+ cj .mu .Lock ()
55+ defer cj .mu .Unlock ()
56+ cj .jar .SetCookies (u , cookies )
57+ }
58+
59+ // Cookies implements http.CookieJar.Cookies
60+ func (cj * CookieJar ) Cookies (u * url.URL ) []* http.Cookie {
61+ if cj .jar == nil {
62+ return nil
63+ }
64+
65+ cj .mu .RLock ()
66+ defer cj .mu .RUnlock ()
67+ return cj .jar .Cookies (u )
68+ }
You can’t perform that action at this time.
0 commit comments