cache

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

http-keystone Cache Middleware

A high-performance, production-ready caching middleware for Echo in Go. → View Full API Documentation

Features

  • Concurrent-safe: Uses sync.Map for high-concurrency environments.
  • Cache stampede prevention: Only one request computes the cache per key; others wait or retry.
  • ETag & Not-Modified: RFC 9110 entity-tags with quoted, list, weak, and * If-None-Match support.
  • Privacy-safe defaults: Authenticated requests, cookies, and non-public responses are never stored unless you opt in.
  • Vary-aware keys: Responses that vary on Accept-Encoding (or headers you configure) get separate cache entries.
  • Configurable: TTL, max body size, retry behavior, skip functions, key generators.
  • Automatic cleanup: Periodic eviction of expired entries prevents memory bloat.
  • Production-ready logging: Tracks hits, misses, and cache events.

Installation

go get github.com/its-ernest/http-keystone@latest

Then import github.com/its-ernest/http-keystone/cache.


Basic Usage

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/labstack/echo/v5"
	"github.com/its-ernest/http-keystone/cache" 
	"github.com/its-ernest/http-keystone/store"
)

func main() {
	e := echo.New()

	// SIMPLE CUSTOM LOGGER
	e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			start := time.Now()
			err := next(c)
			stop := time.Now()
			fmt.Printf("[%s] %d %s %s (%s)\n", 
				stop.Format("15:04:05"),
				c.Request().Method, 
				c.Request().URL.Path,
				stop.Sub(start),
			)
			return err
		}
	})

	// Setup local store
	memStore := store.NewMemoryStore()

	// Apply cache middleware
	e.Use(cache.New(cache.Config{
		Store: memStore,
		TTL:   20 * time.Second,
	}))

	// Echo V5 Handler
	e.GET("/test", func(c *echo.Context) error {
		fmt.Println(" [HANDLER] Generating fresh content...")
		timestamp := time.Now().Format(time.RFC3339Nano)
		return c.String(http.StatusOK, fmt.Sprintf("Generated at: %s", timestamp))
	})

	// Start
	fmt.Println("Starting Dev Server on :8080...")
	if err := e.Start(":8080"); err != nil {
		fmt.Printf("Server stopped: %v\n", err)
	}
}

Configuration Options

Field Type Default Description
Store store.Store Required Backend cache store (MemoryStore, Redis, custom).
TTL time.Duration 5 * time.Minute Time-to-live for cached entries.
Skipper func(*echo.Context) bool nil Function to skip caching for specific requests.
KeyGenerator func(*echo.Context) string DefaultKeyGenerator Base cache key. VaryHeaders and credentials are appended automatically.
MaxBodySize int 1MB Maximum bytes buffered and cached; larger responses stream through uncached.
WeakETag bool false Emit W/"..." validators instead of strong ETags.
RetryDelay time.Duration 20ms Initial delay for a request waiting on another request populating the same key. Grows linearly with up to ±25% jitter.
MaxRetries int 10 Maximum number of polls while waiting for a cold key to be populated.
LockTTL time.Duration 10s How long the population lock is held before another request may take over.
CacheAuthenticated bool false Store responses for requests with Authorization/Cookie, keyed per credential.
CacheableStatusCodes []int [200] Response statuses that may be stored.
VaryHeaders []string ["Accept-Encoding"] Request headers hashed into the key and advertised in Vary.
ShouldCache func(*echo.Context, *store.Entry) bool nil Extra veto after the built-in safety checks.

Cache safety and privacy

The defaults are deliberately conservative, because caching a response for the wrong client is a data leak:

  • Authenticated requests bypass the cache. A request with Authorization, Proxy-Authorization, or Cookie is never served from cache and never stored. Set CacheAuthenticated: true to opt in; credentials are then hashed into the cache key, so different users never share an entry.
  • Only 200 by default. Widen CacheableStatusCodes if you want to cache redirects or 404s.
  • Responses that must stay per-client are never stored: any Set-Cookie, or Cache-Control: private, no-store, or no-cache marks the response as X-Cache: BYPASS.
  • Vary is honored. A response whose Vary names a header that is not in VaryHeaders is not cached, and Vary: * disables caching. Add headers such as Accept-Language to VaryHeaders when handlers vary on them.
  • Request directives are honored. Cache-Control: no-store/no-cache and Pragma: no-cache bypass the cache.
  • Hop-by-hop headers and Set-Cookie are stripped from stored entries and never replayed to another client. Date/Age are regenerated.
  • ShouldCache receives the response entry after the built-in policy and can veto storage for application-specific reasons.

If a route depends on a logged-in user, prefer a stable user or tenant ID in KeyGenerator and leave CacheAuthenticated off, rather than hashing raw session cookies into the key space.


Response size and streaming

The middleware buffers a response only up to MaxBodySize. If a handler writes more than that, or calls Flush (SSE, long polling, websockets), the buffered bytes are sent, the rest of the response is streamed directly to the client, and nothing is stored. Streamed responses carry X-Cache: BYPASS.

This keeps memory bounded by MaxBodySize per in-flight cacheable request instead of by the size of whatever the handler produces.


Conditional requests (ETag / If-None-Match)

Every stored response gets a quoted entity-tag derived from its body: "<sha256>" by default, or W/"<sha256>" when WeakETag is enabled. The same ETag is sent on the first MISS and on later HITs.

On a hit, If-None-Match is parsed per RFC 9110:

  • "etag" matches
  • W/"etag" matches too (If-None-Match uses weak comparison)
  • "other", "etag" — any member of the list matches
  • multiple If-None-Match header lines are combined
  • * matches any stored representation

A match returns 304 Not Modified with no body but with ETag, Vary, and any stored Cache-Control/Expires/Last-Modified/Content-Location, so clients and intermediaries can refresh their metadata. The middleware does not invent Cache-Control: max-age; it preserves whatever the handler set.


Middleware Behavior

  1. Request policy: Non-GET requests, Skipper matches, credential-bearing requests (unless CacheAuthenticated), and no-store/no-cache requests go straight to the handler.
  2. Cache Check: The key is the base key plus a digest of the configured Vary headers (and credentials, when enabled).
  3. Cache Hit: Returns cached response with X-Cache: HIT. ETag validated; returns 304 if client has latest version.
  4. Cache Miss: Acquires lock for this key, re-checks the store, then runs the handler. Only one request populates a cold key.
  5. Other Concurrent Requests: Poll the store with RetryDelay and linear backoff (up to MaxRetries) and replay the populated entry as X-Cache: HIT. If the budget expires, they fail open to the origin handler. Cancellation returns promptly.
  6. Response policy: Status, Set-Cookie, Cache-Control, Vary, and ShouldCache are checked before storing.
  7. Cache Save: Stores a sanitized entry with TTL and an ETag, then serves the same headers with X-Cache: MISS.
  8. Eviction: Expired items removed automatically by the background evictor.

MemoryStore Advanced Features

  • TTL-aware locks: Locks expire automatically to prevent deadlocks.
  • Background eviction: Periodic cleanup of expired cache entries.
  • Concurrent-safe operations: All methods (Get, Save, Delete, Lock, Unlock) are goroutine-safe.
  • Optional singleflight / GetOrCompute can be added for fully atomic cache population.

HTTP Headers

  • X-Cache: HIT, MISS, or BYPASS (not stored)
  • Etag: quoted SHA256 hash of response body (W/"..." with WeakETag)
  • Vary: advertises every configured VaryHeaders entry
  • Content-Type: Respected from handler or auto-detected

Logging

  • Cache HIT / Cache MISS events logged via log.Printf.
  • Fallbacks due to lock contention are logged.
  • Can be replaced with a structured logger in production.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultKeyGenerator

func DefaultKeyGenerator(c *echo.Context) string

DefaultKeyGenerator generates a cache key based on method + URL. VaryHeaders are appended by the middleware, so this key is only the base.

func New

func New(config Config) echo.MiddlewareFunc

New returns an Echo middleware for caching HTTP responses.

By default only anonymous, cacheable GET requests are stored, only 200 responses are kept, and requests carrying Authorization or Cookie headers bypass the cache. See Config for the knobs that relax these defaults.

Types

type Config

type Config struct {
	Store store.Store
	TTL   time.Duration
	// Skipper allows requests to bypass the cache entirely.
	Skipper func(c *echo.Context) bool

	// KeyGenerator produces the base cache key. VaryHeaders are hashed into
	// the key automatically; a custom generator does not need to handle them.
	KeyGenerator func(c *echo.Context) string

	// MaxBodySize prevents caching of massive responses (default 1MB).
	// Responses larger than this are streamed to the client and not cached.
	MaxBodySize int

	// WeakETag emits weak validators (W/"...") instead of strong ones. Use it
	// for bodies whose bytes can change without a semantic change. Default is
	// false (strong ETags).
	WeakETag bool

	// RetryDelay and MaxRetries control what a request does while another
	// request is populating the same cold key. The waiter polls the store up to
	// MaxRetries times, starting at RetryDelay and growing linearly with jitter.
	// Defaults are 20ms and 10 retries (roughly a one-second budget).
	RetryDelay time.Duration
	MaxRetries int

	// LockTTL bounds how long the population lock is held before another
	// request may take it over. Default is 10s. Set it longer than your
	// slowest cacheable handler to avoid concurrent population.
	LockTTL time.Duration

	// CacheAuthenticated allows responses to requests carrying Authorization
	// or Cookie headers to be cached. Default is false.
	//
	// When enabled, Authorization and Cookie values are mixed into the cache
	// key automatically, so different users never share an entry. Prefer a
	// stable user/tenant identifier in KeyGenerator over raw session cookies
	// to keep the key space manageable.
	CacheAuthenticated bool

	// CacheableStatusCodes is the allow-list of response statuses that may be
	// stored. Default is []int{http.StatusOK}.
	CacheableStatusCodes []int

	// VaryHeaders lists request headers that are hashed into the cache key and
	// advertised in the response Vary header. Default is
	// []string{"Accept-Encoding"}.
	//
	// A response whose Vary header names a header that is not in this list is
	// not cached, because doing so could serve the wrong representation.
	// Add headers such as "Accept-Language" here when handlers vary on them.
	VaryHeaders []string

	// ShouldCache runs after the built-in safety policy (status allow-list,
	// Cache-Control, Set-Cookie, Vary) and can further restrict caching.
	ShouldCache func(c *echo.Context, entry *store.Entry) bool
}

Config structure for http-keystone/cache middleware

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL