Skip to content
This repository was archived by the owner on Apr 20, 2023. It is now read-only.

Commit d79f2a3

Browse files
committed
Add ShouldCache option
1 parent 7a0d97d commit d79f2a3

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

‎httpcache.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,9 @@ type Transport struct {
105105
// a successful response from the cache will be returned without connecting to the server.
106106
AlwaysUseCachedResponse func(req *http.Request, key string) bool
107107

108+
// ShouldCache is an optional func that when it returns false, the response will not be cached.
109+
ShouldCache func(req *http.Request, resp *http.Response, key string) bool
110+
108111
// Around is an optional func.
109112
// If set, the Transport will call Around at the start of RoundTrip
110113
// and defer the returned func until the end of RoundTrip.
@@ -228,7 +231,7 @@ func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error
228231
}
229232
}
230233

231-
if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) {
234+
if cacheable && (t.ShouldCache == nil || t.ShouldCache(req, resp, cacheKey)) && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) {
232235
for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") {
233236
varyKey = http.CanonicalHeaderKey(varyKey)
234237
fakeHeader := "X-Varied-" + varyKey

‎httpcache_test.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,8 @@ func cacheSize() int {
178178
func resetTest() {
179179
s.transport.Cache = newMemoryCache()
180180
s.transport.CacheKey = nil
181+
s.transport.AlwaysUseCachedResponse = nil
182+
s.transport.ShouldCache = nil
181183
s.transport.EnableETagPair = false
182184
s.transport.MarkCachedResponses = false
183185
clock = &realClock{}
@@ -269,6 +271,30 @@ func TestAlwaysUseCachedResponse(t *testing.T) {
269271
}
270272
}
271273

274+
func TestShouldCache(t *testing.T) {
275+
resetTest()
276+
c := qt.New(t)
277+
s.transport.AlwaysUseCachedResponse = func(req *http.Request, key string) bool {
278+
return true
279+
}
280+
281+
s.transport.ShouldCache = func(req *http.Request, resp *http.Response, key string) bool {
282+
return req.Header.Get("Hello") == "world2"
283+
}
284+
{
285+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world1"})
286+
c.Assert(s, qt.Equals, "world1")
287+
}
288+
{
289+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world2"})
290+
c.Assert(s, qt.Equals, "world2")
291+
}
292+
{
293+
s, _ := doMethod(t, "GET", "/helloheaderasbody", map[string]string{"Hello": "world3"})
294+
c.Assert(s, qt.Equals, "world2")
295+
}
296+
}
297+
272298
func TestAround(t *testing.T) {
273299
resetTest()
274300
c := qt.New(t)

0 commit comments

Comments
 (0)