Skip to content

Commit

Permalink
Add AroundRoundTrip option, unexport CachedResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed May 17, 2024
1 parent 10eb476 commit 605d990
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions httpcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ func cacheKey(req *http.Request) string {
}
}

// CachedResponse returns the cached http.Response for req if present, and nil
// cachedResponse returns the cached http.Response for req if present, and nil
// otherwise.
func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
func cachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
cachedVal, ok := c.Get(cacheKey(req))
if !ok {
return
Expand Down Expand Up @@ -98,9 +98,18 @@ type Transport struct {
// The RoundTripper interface actually used to make requests
// If nil, http.DefaultTransport is used
Transport http.RoundTripper
Cache Cache

// The Cache interface used to store and retrieve responses.
Cache Cache

// If true, responses returned from the cache will be given an extra header, X-From-Cache
MarkCachedResponses bool

// AroundRoundTrip is an optional func.
// If set, the Transport will call AroundRoundTrip at the start of RoundTrip
// and defer the returned func until the end of RoundTrip.
// Typically used to implement a lock that is held for the duration of the RoundTrip.
AroundRoundTrip func(key string) func()
}

// NewTransport returns a new Transport with the
Expand Down Expand Up @@ -136,10 +145,13 @@ func varyMatches(cachedResp *http.Response, req *http.Request) bool {
// will be returned.
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
cacheKey := cacheKey(req)
if n := t.AroundRoundTrip; n != nil {
defer n(cacheKey)()
}
cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == ""
var cachedResp *http.Response
if cacheable {
cachedResp, err = CachedResponse(t.Cache, req)
cachedResp, err = cachedResponse(t.Cache, req)
} else {
// Need to invalidate an existing value
t.Cache.Delete(cacheKey)
Expand Down

0 comments on commit 605d990

Please sign in to comment.