Documentation
¶
Index ¶
- type CacheKey
- type CacheStatusMode
- type Option
- func WithAutoInvalidateMutatingMethods() Option
- func WithBackgroundFetchTimeout(d time.Duration) Option
- func WithCacheKey(k CacheKey) Option
- func WithCacheStatusMode(mode CacheStatusMode) Option
- func WithConvertHeadToGet(enable bool) Option
- func WithESI(opts ...esi.Option) Option
- func WithLogger(l *slog.Logger) Option
- func WithMetrics(reg prometheus.Registerer) Option
- func WithRespectClientCacheControl() Option
- func WithStorage(s storage.Storage) Option
- func WithStorageTimeout(d time.Duration) Option
- func WithTagHeaderName(name string) Option
- type PurgeOption
- type Titip
- func (t *Titip) Close(ctx context.Context) error
- func (t *Titip) Purge(ctx context.Context, target string, opts ...PurgeOption) (int64, error)
- func (t *Titip) PurgeAll(ctx context.Context) (int64, error)
- func (t *Titip) PurgeTag(ctx context.Context, tag string, opts ...PurgeOption) (int64, error)
- func (t *Titip) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.Handler)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CacheKey ¶ added in v0.2.0
type CacheKey struct {
// IncludeProtocol includes the request scheme ("http" or "https") in the cache key.
// When true, HTTP and HTTPS requests reference distinct cache entries.
IncludeProtocol bool
// ExcludeHost excludes the HTTP Host / domain from the cache key.
// When true, Host is omitted so multiple domains serving identical content share cache entries.
ExcludeHost bool
// ExcludeQueryString removes all query parameters from the cache key.
// When true, all query parameters are stripped so requests with different query strings share cache.
ExcludeQueryString bool
// DisableQueryStringSort preserves the original query parameter ordering from the request URL.
// When true, query parameter order is preserved as received from the client.
DisableQueryStringSort bool
// IncludedQueryParams specifies an allowlist of query parameter names to include in the cache key.
// If set, only these specific parameters are included in the cache key.
IncludedQueryParams []string
// ExcludedQueryParams specifies a denylist of query parameter names to exclude from the cache key.
// If set, all query parameters except these are included in the cache key.
ExcludedQueryParams []string
// ExcludeMarketingParams filters out standard advertising and tracking query parameters
// (e.g. utm_source, utm_campaign, utm_medium, gclid, fbclid, ttclid).
// When true, marketing tracking parameters are stripped from the cache key.
ExcludeMarketingParams bool
// IncludedHeaderNames specifies request header names whose values are appended to the primary cache key.
//
// Note: Do NOT include headers that the origin already manages via the HTTP "Vary" header
// (e.g. "Accept-Encoding"), as Titip handles origin Vary negotiation automatically.
//
// Warning: NEVER include authentication tokens or credentials (e.g. "Authorization").
// Specifying headers with high cardinality or wide ranges of values dramatically lowers the
// cache hit rate and causes higher eviction churn.
//
// Best used for low-cardinality headers or A/B experiment buckets (e.g. "X-Region", "X-Experiment-Bucket").
IncludedHeaderNames []string
// IncludedCookieNames specifies cookie names whose values are appended to the cache key.
//
// Warning: NEVER include session identifiers, auth cookies, or credentials.
// Including unique per-user cookies effectively creates per-user caches, destroying hit rates.
//
// Best used for low-cardinality user preferences or A/B testing groups (e.g. "ab_group", "currency", "theme", "locale").
IncludedCookieNames []string
// CaseInsensitivePath normalizes the URL path to lowercase in the primary cache key.
// When true, requests with different path casing (e.g. /Products/Shoes vs /products/shoes) share the same cache entry.
CaseInsensitivePath bool
// IncludedQueryParamValues specifies an allowlist of specific parameter values.
// A parameter key in this map is only included in the cache key if its value matches one of the specified allowed values.
// Any value not in the list is omitted from the cache key.
IncludedQueryParamValues map[string][]string
}
CacheKey defines the rules for assembling zero-hash canonical cache keys.
Every cached request automatically receives a cache key. A zero-value CacheKey{} or omitting WithCacheKey applies the standard RFC-compliant default: host included, protocol excluded, case-sensitive path, all query parameters retained, and sorted alphabetically.
type CacheStatusMode ¶
type CacheStatusMode int
CacheStatusMode specifies the format of the emitted Cache-Status header.
const ( // CacheStatusSimpleToken outputs single-token status header (e.g. HIT, MISS, EXPIRED, REVALIDATED, UPDATING, STALE, BYPASS, DYNAMIC) by default. CacheStatusSimpleToken CacheStatusMode = iota // CacheStatusRFC9211 outputs structured RFC-9211 Cache-Status header (e.g. Cache-Status: titip; hit; ttl=240). CacheStatusRFC9211 // CacheStatusNone disables cache status header generation. CacheStatusNone )
type Option ¶
type Option func(*config)
Option configures Titip middleware options.
func WithAutoInvalidateMutatingMethods ¶
func WithAutoInvalidateMutatingMethods() Option
WithAutoInvalidateMutatingMethods enables automatic invalidation of cached GET entries when successful mutating requests (POST, PUT, DELETE, PATCH) are received for the URI, matching the mandatory invalidation behavior defined in RFC 9111 Section 4.4. By default, this is disabled so applications can rely on explicit tag-based (Cache-Tag) or URL invalidation.
func WithBackgroundFetchTimeout ¶ added in v0.2.0
WithBackgroundFetchTimeout configures the maximum timeout for asynchronous background revalidation (stale-while-revalidate) origin fetches (defaults to 125s). Set to 0 or negative to disable background timeout enforcement.
func WithCacheKey ¶ added in v0.2.0
WithCacheKey customizes the rules for assembling canonical cache keys (such as query parameter filtering, marketing tag removal, and header/cookie dimensions).
A cache key is always automatically generated for every request. If WithCacheKey is omitted, Titip applies standard default key generation (protocol-agnostic, host-aware, case-sensitive path, all query parameters retained, and sorted alphabetically).
func WithCacheStatusMode ¶
func WithCacheStatusMode(mode CacheStatusMode) Option
WithCacheStatusMode configures Cache-Status header mode.
func WithConvertHeadToGet ¶
WithConvertHeadToGet configures whether HEAD cache misses and revalidations are converted to GET when fetching from the upstream origin to prime the cache (defaults to true). When false, HEAD misses query the origin as HEAD and are not saved to cache.
func WithESI ¶
WithESI enables ESI processing with the provided ESI options. If no options are provided, ESI is enabled with safe production defaults.
func WithLogger ¶
WithLogger configures the structured slog.Logger.
func WithMetrics ¶
func WithMetrics(reg prometheus.Registerer) Option
WithMetrics configures the Prometheus metrics registerer.
func WithRespectClientCacheControl ¶
func WithRespectClientCacheControl() Option
WithRespectClientCacheControl enables respecting client request Cache-Control directives (e.g. no-cache, no-store). By default, client cache directives are ignored to protect origin servers.
func WithStorage ¶
WithStorage configures the backend cache storage engine.
func WithStorageTimeout ¶
WithStorageTimeout configures maximum timeout for storage operations (defaults to 1s).
func WithTagHeaderName ¶
WithTagHeaderName configures the response header inspected for cache tags (defaults to "Cache-Tag").
type PurgeOption ¶
type PurgeOption func(*purgeConfig)
PurgeOption configures Purge, PurgeTag, or PurgeAll operations.
func WithSoftPurge ¶
func WithSoftPurge() PurgeOption
WithSoftPurge marks entries as stale rather than evicting immediately (safe thundering-herd mode). The stale copy is preserved for stale-if-error fallback if the origin subsequently fails.
type Titip ¶
type Titip struct {
// contains filtered or unexported fields
}
Titip represents the HTTP caching middleware instance.
func (*Titip) Close ¶
Close cleanly shuts down the middleware, awaiting background SWR revalidations.
func (*Titip) Purge ¶
Purge invalidates cache entries matching the specified path, URL, exact query variant, or wildcard.
The target supports four formats:
- "/api/products" — purges the path and ALL query string variations
- "/api/products?id=42" — purges only this exact query variant
- "/assets/*" — wipes all cached paths under /assets/ (wildcard)
- "https://example.com/api" — host-scoped path purge (include domain in target to scope by host)
By default, purge is a hard-delete (immediate physical eviction). Use WithSoftPurge() to mark entries as stale instead for safe thundering-herd protection.
Returns the total number of logical cache entries invalidated.