|
| 1 | +package capsulecache |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "crypto/sha256" |
| 6 | + "encoding/hex" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// Config holds the middleware settings. |
| 14 | +type Config struct { |
| 15 | + // DefaultTTL is how long a cached entry is considered fresh. |
| 16 | + DefaultTTL time.Duration |
| 17 | + // DefaultSWR is the stale-while-revalidate window. |
| 18 | + DefaultSWR time.Duration |
| 19 | + KeyGenerator func(*http.Request) string |
| 20 | + // ShouldCache decides whether a response with given status code should be cached. |
| 21 | + ShouldCache func(statusCode int) bool |
| 22 | + // MaxBodyBytes - do not cache bodies larger than this. |
| 23 | + MaxBodyBytes int64 |
| 24 | + // StripHeaders removes headers before storing (hop-by-hop etc). |
| 25 | + StripHeaders func(http.Header) http.Header |
| 26 | +} |
| 27 | + |
| 28 | +// DefaultConfig provides defaults. |
| 29 | +var DefaultConfig = &Config{ |
| 30 | + DefaultTTL: 5 * time.Minute, |
| 31 | + DefaultSWR: 1 * time.Minute, |
| 32 | + KeyGenerator: DefaultKeyGenerator, |
| 33 | + ShouldCache: func(statusCode int) bool { |
| 34 | + // Only cache successful responses by default |
| 35 | + return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices |
| 36 | + }, |
| 37 | + StripHeaders: stripHopByHop, |
| 38 | +} |
| 39 | + |
| 40 | +// DefaultKeyGenerator creates a simple cache key (Method:Path). |
| 41 | +func DefaultKeyGenerator(r *http.Request) string { |
| 42 | + return "cache:" + r.Method + ":" + r.URL.Path |
| 43 | +} |
| 44 | + |
| 45 | +// AdvancedKeyGenerator includes specified headers and body hash (for POST/PUT). |
| 46 | +func AdvancedKeyGenerator(r *http.Request, headersToInclude []string) string { |
| 47 | + // 1. Base Key |
| 48 | + key := r.Method + ":" + r.URL.Path |
| 49 | + |
| 50 | + // 2. Add Headers |
| 51 | + for _, header := range headersToInclude { |
| 52 | + if val := r.Header.Get(header); val != "" { |
| 53 | + key += ":" + header + "=" + val |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // 3. Add Body Hash (for safe caching of idempotent requests like POST to a search endpoint) |
| 58 | + if r.ContentLength > 0 && (r.Method == http.MethodPost || r.Method == http.MethodPut) { |
| 59 | + var buf bytes.Buffer |
| 60 | + // TeeReader allows reading the body while writing it to buf |
| 61 | + tee := io.TeeReader(r.Body, &buf) |
| 62 | + bodyBytes, _ := io.ReadAll(tee) |
| 63 | + r.Body.Close() |
| 64 | + r.Body = io.NopCloser(&buf) // restore body for downstream |
| 65 | + |
| 66 | + hash := sha256.Sum256(bodyBytes) |
| 67 | + key += ":body_hash=" + hex.EncodeToString(hash[:]) |
| 68 | + } |
| 69 | + |
| 70 | + return key |
| 71 | +} |
| 72 | + |
| 73 | +func stripHopByHop(header http.Header) http.Header { |
| 74 | + // Clone so caller can mutate safely. |
| 75 | + headerClone := header.Clone() |
| 76 | + |
| 77 | + for _, k := range []string{ |
| 78 | + "Connection", "Proxy-Connection", "Keep-Alive", |
| 79 | + "Proxy-Authenticate", "Proxy-Authorization", "TE", |
| 80 | + "Trailer", "Transfer-Encoding", "Upgrade", |
| 81 | + } { |
| 82 | + headerClone.Del(k) |
| 83 | + } |
| 84 | + // Also remove hop-by-hop values referenced by Connection header |
| 85 | + if conn := header.Get("Connection"); conn != "" { |
| 86 | + for _, token := range strings.Split(conn, ",") { |
| 87 | + token = strings.TrimSpace(token) |
| 88 | + if token != "" { |
| 89 | + headerClone.Del(token) |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + return headerClone |
| 94 | +} |
0 commit comments