Skip to content

Commit 0250321

Browse files
committed
Add AlwaysUseCachedResponse option func
1 parent 135302a commit 0250321

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

‎httpcache.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ type Transport struct {
101101
// An empty string signals that this request should not be cached.
102102
CacheKey func(req *http.Request) string
103103

104+
// AlwaysUseCachedResponse is an optional func that when it returns true
105+
// a successful response from the cache will be returned without connecting to the server.
106+
AlwaysUseCachedResponse func(req *http.Request, key string) bool
107+
104108
// Around is an optional func.
105109
// If set, the Transport will call Around at the start of RoundTrip
106110
// and defer the returned func until the end of RoundTrip.
@@ -141,6 +145,9 @@ func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error
141145
var cachedResp *http.Response
142146
if cacheable {
143147
cachedResp, err = t.cachedResponse(req)
148+
if err == nil && cachedResp != nil && t.AlwaysUseCachedResponse != nil && t.AlwaysUseCachedResponse(req, cacheKey) {
149+
return cachedResp, nil
150+
}
144151
} else {
145152
// Need to invalidate an existing value
146153
t.Cache.Delete(cacheKey)

‎httpcache_test.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,27 @@ func TestEnableETagPair(t *testing.T) {
248248
}
249249
}
250250

251+
func TestAlwaysUseCachedResponse(t *testing.T) {
252+
resetTest()
253+
c := qt.New(t)
254+
s.transport.AlwaysUseCachedResponse = func(req *http.Request, key string) bool {
255+
return req.Header.Get("Hello") == "world2"
256+
}
257+
258+
{
259+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world1"})
260+
c.Assert(s, qt.Equals, "world1")
261+
}
262+
{
263+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world2"})
264+
c.Assert(s, qt.Equals, "world1")
265+
}
266+
{
267+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world3"})
268+
c.Assert(s, qt.Equals, "world3")
269+
}
270+
}
271+
251272
func TestAround(t *testing.T) {
252273
resetTest()
253274
c := qt.New(t)

0 commit comments

Comments
 (0)