Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookiejar implementation. #526

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ type Client struct {
// User-Agent header to be excluded from the Request.
NoDefaultUserAgentHeader bool

// CookieJar stores cookies allowing user to handle cookies easily.
//
// If CookieJar is nil no cookie will be collected.
CookieJar *CookieJar

// Callback for establishing new connections to hosts.
//
// Default Dial is used if not set.
Expand Down Expand Up @@ -410,6 +415,7 @@ func (c *Client) Do(req *Request, resp *Response) error {
Name: c.Name,
NoDefaultUserAgentHeader: c.NoDefaultUserAgentHeader,
Dial: c.Dial,
CookieJar: c.CookieJar,
DialDualStack: c.DialDualStack,
IsTLS: isTLS,
TLSConfig: c.TLSConfig,
Expand Down Expand Up @@ -525,6 +531,10 @@ type HostClient struct {
// Default Dial is used if not set.
Dial DialFunc

// CookieJar stores cookies. If CookieJar is nil
// no cookie will be collected.
CookieJar *CookieJar

// Attempt to connect to both ipv4 and ipv6 host addresses
// if set to true.
//
Expand Down Expand Up @@ -1101,8 +1111,17 @@ func (c *HostClient) do(req *Request, resp *Response) (bool, error) {
resp = AcquireResponse()
}

host := b2s(req.Host())
dgrr marked this conversation as resolved.
Show resolved Hide resolved
if c.CookieJar != nil {
c.CookieJar.dumpTo(host, req)
}

ok, err := c.doNonNilReqResp(req, resp)

if c.CookieJar != nil {
c.CookieJar.getFrom(host, resp)
}

if nilResp {
ReleaseResponse(resp)
}
Expand Down
38 changes: 38 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,44 @@ func TestClientPostArgs(t *testing.T) {
}
}

func TestClientCookieJar(t *testing.T) {
ln := fasthttputil.NewInmemoryListener()
key, value := "cometo", "thefasthttpcon"
s := &Server{
Handler: func(ctx *RequestCtx) {
cookie := AcquireCookie()
cookie.SetKey(key)
cookie.SetValue(value)
ctx.Response.Header.SetCookie(cookie)
},
}
go s.Serve(ln)
c := &Client{
Dial: func(addr string) (net.Conn, error) {
return ln.Dial()
},
CookieJar: &CookieJar{},
}
req := AcquireRequest()
res := AcquireResponse()
req.SetRequestURI("http://fasthttp.con/hello/world")
err := c.Do(req, res)
if err != nil {
t.Fatal(err)
}
cs := c.CookieJar.Get("fasthttp.con")
if len(cs) == 0 {
t.Fatalf("Unexpected len: %d", len(cs))
}

if k := string(cs[0].Key()); k != key {
t.Fatalf("Unexpected key: %s <> %s", k, key)
}
if v := string(cs[0].Value()); v != value {
t.Fatalf("Unexpected value: %s <> %s", v, value)
}
}

func TestClientRedirectSameSchema(t *testing.T) {

listenHTTPS1 := testClientRedirectListener(t, true)
Expand Down
1 change: 1 addition & 0 deletions cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var (
// CookieSameSite is an enum for the mode in which the SameSite flag should be set for the given cookie.
// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
type CookieSameSite int

const (
// CookieSameSiteDisabled removes the SameSite flag
CookieSameSiteDisabled CookieSameSite = iota
Expand Down
80 changes: 80 additions & 0 deletions cookiejar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package fasthttp

import (
"sync"
)

// CookieJar manages cookie storage
type CookieJar struct {
m sync.RWMutex
hostCookies map[string][]*Cookie
dgrr marked this conversation as resolved.
Show resolved Hide resolved
}

// Get returns the cookies stored from a specific domain.
//
// If there were no cookies related with host returned slice will be nil.
func (cj *CookieJar) Get(host string) (cookies []*Cookie) {
cj.m.RLock()
{
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]*Cookie)
dgrr marked this conversation as resolved.
Show resolved Hide resolved
dgrr marked this conversation as resolved.
Show resolved Hide resolved
}
cookies = cj.hostCookies[host]
}
cj.m.RUnlock()
return
}

// Set sets cookies for a specific host.
func (cj *CookieJar) Set(host string, cookies ...*Cookie) {
cj.m.Lock()
{
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]*Cookie)
}
hc := cj.hostCookies[host]
hc = append(hc, cookies...)
cj.hostCookies[host] = hc
}
cj.m.Unlock()
}

func (cj *CookieJar) dumpTo(host string, req *Request) {
cj.m.Lock()
{
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]*Cookie)
dgrr marked this conversation as resolved.
Show resolved Hide resolved
}
cookies, ok := cj.hostCookies[host]
if ok {
for _, cookie := range cookies {
req.Header.SetCookieBytesKV(cookie.Key(), cookie.Value())
}
}
}
cj.m.Unlock()
}

func (cj *CookieJar) getFrom(host string, res *Response) {
cj.m.Lock()
{
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]*Cookie)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you can just do return. No need to allocate anything.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just make sure you do defer cj.m.Unlock() instead of doing this at the end of the function.

I myself always prefer to defer Unlocks as its much easier to follow the code. Also defer is basically free these days so no worry about performance.

}
cookies, ok := cj.hostCookies[host]
if !ok {
cookies = make([]*Cookie, 0)
dgrr marked this conversation as resolved.
Show resolved Hide resolved
}
res.Header.VisitAllCookie(func(key, value []byte) {
cookie := &Cookie{}
dgrr marked this conversation as resolved.
Show resolved Hide resolved
cookie.SetKeyBytes(key)
if !res.Header.Cookie(cookie) {
// TODO: error?
cookie.SetValueBytes(value)
}
dgrr marked this conversation as resolved.
Show resolved Hide resolved
cookies = append(cookies, cookie)
dgrr marked this conversation as resolved.
Show resolved Hide resolved
})
cj.hostCookies[host] = cookies
}
cj.m.Unlock()
}
50 changes: 50 additions & 0 deletions cookiejar_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package fasthttp

import "testing"

func prepareJar() *CookieJar {
cj := &CookieJar{}
cj.hostCookies = make(map[string][]*Cookie)
return cj
}

func checkKeyValue(t *testing.T, cj *CookieJar, cookie *Cookie, host string, n int) {
cs := cj.Get(host)
if len(cs) < n {
t.Fatalf("Unexpected cookie length: %d. Expected %d", len(cs), n)
}
c := cs[n-1]
if c == nil {
t.Fatal("got a nil cookie")
}
if string(c.Key()) != string(cookie.Key()) {
t.Fatalf("key mismatch: %s <> %s", c.Key(), cookie.Key())
}
if string(c.Value()) != string(cookie.Value()) {
t.Fatalf("value mismatch: %s <> %s", c.Value(), cookie.Value())
}
}

func TestCookieJar_Get(t *testing.T) {
host := "fast.http"
cj := prepareJar()

cookie := &Cookie{}
cookie.SetKey("k")
cookie.SetValue("v")

cj.hostCookies[host] = append(cj.hostCookies[host], cookie)
checkKeyValue(t, cj, cookie, host, 1)
}

func TestCookieJar_Set(t *testing.T) {
host := "fast.http"
cj := &CookieJar{}

cookie := &Cookie{}
cookie.SetKey("k")
cookie.SetValue("v")

cj.Set(host, cookie)
checkKeyValue(t, cj, cookie, host, 1)
}