Skip to content

Commit

Permalink
Merge pull request #39 from 2manymws/ignore-set-cookie
Browse files Browse the repository at this point in the history
Does not store responses with Set-Cookie headers by default, similar to NGINX
  • Loading branch information
k1LoW authored Dec 20, 2023
2 parents 45b3316 + c738736 commit 337bbda
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions rfc9111/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type Shared struct {
understoodStatusCodes []int
heuristicallyCacheableStatusCodes []int
heuristicExpirationRatio float64
storeRequestWithSetCookieHeader bool
extendedRules []ExtendedRule
}

Expand Down Expand Up @@ -65,6 +66,14 @@ func HeuristicExpirationRatio(ratio float64) SharedOption {
}
}

// StoreRequestWithSetCookieHeader enables storing request with Set-Cookie header.
func StoreRequestWithSetCookieHeader() SharedOption {
return func(s *Shared) error {
s.storeRequestWithSetCookieHeader = true
return nil
}
}

// ExtendedRules sets the extended rules.
func ExtendedRules(rules []ExtendedRule) SharedOption {
return func(s *Shared) error {
Expand Down Expand Up @@ -144,6 +153,13 @@ func (s *Shared) Storable(req *http.Request, res *http.Response, now time.Time)
return false, time.Time{}
}

// In RFC 9111, Servers that wish to control caching of responses with Set-Cookie headers are encouraged to emit appropriate Cache-Control response header fields (see https://httpwg.org/specs/rfc9111.html#rfc.section.7.3).
// But to beat on the safe side, this package does not store responses with Set-Cookie headers by default, similar to NGINX.
// THIS IS NOT RFC 9111.
if req.Header.Get("Set-Cookie") != "" && !s.storeRequestWithSetCookieHeader {
return false, time.Time{}
}

expires := CalclateExpires(rescc, res.Header, s.heuristicExpirationRatio, now)
if expires.Sub(now) <= 0 {
if expires.Sub(time.Time{}) == 0 {
Expand Down
18 changes: 18 additions & 0 deletions rfc9111/shared_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,24 @@ func TestShared_Storable(t *testing.T) {
false,
time.Time{},
},
{
"GET Set-Cookie: k=v 200 Cache-Control: max-age=15 -> No Store",
&http.Request{
Method: http.MethodGet,
Header: http.Header{
"Set-Cookie": []string{"k=v"},
},
},
&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Cache-Control": []string{"max-age=15"},
},
},
nil,
false,
time.Time{},
},
{
"ExtendedRule(+15s) GET 200 -> +15s",
&http.Request{
Expand Down

0 comments on commit 337bbda

Please sign in to comment.