Skip to content

Commit

Permalink
Add AlwaysUseCachedResponse option func
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed May 21, 2024
1 parent 135302a commit 0250321
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions httpcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ type Transport struct {
// An empty string signals that this request should not be cached.
CacheKey func(req *http.Request) string

// AlwaysUseCachedResponse is an optional func that when it returns true
// a successful response from the cache will be returned without connecting to the server.
AlwaysUseCachedResponse func(req *http.Request, key string) bool

// Around is an optional func.
// If set, the Transport will call Around at the start of RoundTrip
// and defer the returned func until the end of RoundTrip.
Expand Down Expand Up @@ -141,6 +145,9 @@ func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error
var cachedResp *http.Response
if cacheable {
cachedResp, err = t.cachedResponse(req)
if err == nil && cachedResp != nil && t.AlwaysUseCachedResponse != nil && t.AlwaysUseCachedResponse(req, cacheKey) {
return cachedResp, nil
}
} else {
// Need to invalidate an existing value
t.Cache.Delete(cacheKey)
Expand Down
21 changes: 21 additions & 0 deletions httpcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,27 @@ func TestEnableETagPair(t *testing.T) {
}
}

func TestAlwaysUseCachedResponse(t *testing.T) {
resetTest()
c := qt.New(t)
s.transport.AlwaysUseCachedResponse = func(req *http.Request, key string) bool {
return req.Header.Get("Hello") == "world2"
}

{
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world1"})
c.Assert(s, qt.Equals, "world1")
}
{
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world2"})
c.Assert(s, qt.Equals, "world1")
}
{
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world3"})
c.Assert(s, qt.Equals, "world3")
}
}

func TestAround(t *testing.T) {
resetTest()
c := qt.New(t)
Expand Down

0 comments on commit 0250321

Please sign in to comment.