RoundTrip implements http.RoundTripper
(req Request)
| 31 | |
| 32 | // RoundTrip implements http.RoundTripper |
| 33 | func (c cachingWare) RoundTrip(req Request) (*http.Response, error) { |
| 34 | // short circuit everything if there cache is no cache |
| 35 | if c.cache == nil { |
| 36 | return c.next.RoundTrip(req) |
| 37 | } |
| 38 | |
| 39 | // extract cache key |
| 40 | key := req.CacheKey() |
| 41 | if len(key) > 0 { |
| 42 | body := c.cache.fetchBytes(req.Context(), key) |
| 43 | if len(body) > 0 { |
| 44 | contentType := determineContentType(body) |
| 45 | |
| 46 | resp := &http.Response{ |
| 47 | Header: http.Header{api.HeaderContentType: []string{contentType}, combiner.TempoCacheHeader: []string{combiner.TempoCacheHit}}, |
| 48 | StatusCode: http.StatusOK, |
| 49 | Status: http.StatusText(http.StatusOK), |
| 50 | Body: io.NopCloser(bytes.NewBuffer(body)), |
| 51 | ContentLength: int64(len(body)), |
| 52 | } |
| 53 | |
| 54 | return resp, nil |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | resp, err := c.next.RoundTrip(req) |
| 59 | |
| 60 | // Add cache miss header for all responses that weren't from cache |
| 61 | if resp != nil { |
| 62 | if resp.Header == nil { |
| 63 | resp.Header = http.Header{} |
| 64 | } |
| 65 | resp.Header[combiner.TempoCacheHeader] = []string{combiner.TempoCacheMiss} |
| 66 | } |
| 67 | |
| 68 | // do not cache if there was an error |
| 69 | if err != nil { |
| 70 | return resp, err |
| 71 | } |
| 72 | |
| 73 | // do not cache if response is not HTTP 2xx |
| 74 | if !shouldCache(resp.StatusCode) { |
| 75 | return resp, nil |
| 76 | } |
| 77 | |
| 78 | if len(key) > 0 { |
| 79 | // don't bother caching if the response is too large |
| 80 | maxItemSize := c.cache.c.MaxItemSize() |
| 81 | if maxItemSize > 0 && resp.ContentLength > int64(maxItemSize) { |
| 82 | return resp, nil |
| 83 | } |
| 84 | |
| 85 | buffer, err := api.ReadBodyToBuffer(resp) |
| 86 | if err != nil { |
| 87 | return resp, fmt.Errorf("failed to cache: %w", err) |
| 88 | } |
| 89 | |
| 90 | // reset the body so the caller can read it |
nothing calls this directly
no test coverage detected