Documentation
¶
Overview ¶
Package cache provides a size-bounded in-memory LRU cache for static files. It wraps github.com/hashicorp/golang-lru/v2 and tracks total byte usage to enforce a maximum memory ceiling independent of item count.
Index ¶
Constants ¶
const ( // HTTPTimeFormat is the time format used for HTTP Date, Last-Modified, // and Expires headers. It is identical to the value of net/http.TimeFormat // but defined here to avoid importing net/http in the cache package. HTTPTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is a thread-safe, size-bounded LRU cache for CachedFile entries.
func NewCache ¶
NewCache creates a new Cache with the given maximum byte capacity. If maxBytes is <= 0, a default of 256 MB is used. If ttl is provided and > 0, entries expire after that duration.
func (*Cache) Get ¶
func (c *Cache) Get(path string) (*CachedFile, bool)
Get returns the cached file for the given path key, or (nil, false) on miss.
func (*Cache) Preload ¶ added in v1.3.0
func (c *Cache) Preload(root string, cfg PreloadConfig) PreloadStats
Preload walks root and loads every eligible regular file into the cache. Files larger than cfg.MaxFileSize or whose path contains dotfile segments (when cfg.BlockDotfiles is true) are skipped. The function returns stats describing what was loaded.
func (*Cache) Put ¶
func (c *Cache) Put(path string, f *CachedFile)
Put stores a file in the cache under the given path key. If adding the new entry would exceed maxBytes, it evicts LRU entries until enough space is available. If the single entry is larger than maxBytes, it is not cached.
func (*Cache) Stats ¶
func (c *Cache) Stats() CacheStats
Stats returns a snapshot of current cache statistics.
type CacheStats ¶
type CacheStats struct {
// Hits is the total number of successful cache lookups.
Hits int64
// Misses is the total number of failed cache lookups.
Misses int64
// CurrentBytes is the current total byte usage.
CurrentBytes int64
// EntryCount is the current number of entries.
EntryCount int
}
CacheStats holds runtime statistics for the cache.
type CachedFile ¶
type CachedFile struct {
// Data is the raw (uncompressed) file content.
Data []byte
// GzipData is the pre-compressed gzip content, or nil if unavailable.
GzipData []byte
// BrData is the pre-compressed brotli content, or nil if unavailable.
BrData []byte
// ETag is the first 16 hex characters of sha256(Data), without quotes.
ETag string
// ETagFull is the pre-formatted weak ETag ready for use in HTTP headers,
// e.g. `W/"abc123"`. Pre-computing it avoids a per-request string alloc.
ETagFull string
// LastModified is the file's modification time.
LastModified time.Time
// ContentType is the detected MIME type.
ContentType string
// Size is the length of Data in bytes.
Size int64
// ExpiresAt is the cache entry expiry time. Zero means no expiry.
ExpiresAt time.Time
// Pre-formatted header values avoid per-request string formatting.
// These are populated by InitHeaders() or by the preload path.
// With fasthttp, headers are set via Set(key, value) taking plain strings;
// an empty string means "not initialised".
CTHeader string // e.g. "text/html; charset=utf-8"
CLHeader string // e.g. "2943" — raw data Content-Length
// Pre-formatted cache/conditional headers (PERF-003).
// Populated by InitHeaders(); the serving hot path assigns these
// directly to the response header, skipping all formatting.
ETagHeader string // e.g. `W/"abc123"`
LastModHeader string // e.g. "Mon, 15 Jan 2024 10:00:00 GMT"
VaryHeader string // e.g. "Accept-Encoding"
CacheControlHeader string // e.g. "public, max-age=3600"
}
CachedFile holds the content and metadata for a single cached file.
func (*CachedFile) InitCacheControl ¶ added in v1.3.0
func (f *CachedFile) InitCacheControl(urlPath string, htmlMaxAge, staticMaxAge int, immutablePattern string)
InitCacheControl pre-formats the Cache-Control header for a specific URL path and header configuration. This must be called after InitHeaders(). urlPath is used to determine HTML vs static max-age; isHTML reports whether the file is an HTML document; immutablePattern is the glob for immutable files.
func (*CachedFile) InitHeaders ¶ added in v1.3.0
func (f *CachedFile) InitHeaders()
InitHeaders pre-formats the Content-Type, Content-Length, ETag, Last-Modified, and Vary header strings so that the serving hot path can assign them directly without allocating (PERF-003). This is idempotent.
type PreloadConfig ¶ added in v1.3.0
type PreloadConfig struct {
// MaxFileSize is the maximum individual file size to preload.
MaxFileSize int64
// IndexFile is the index filename for directory requests (e.g. "index.html").
IndexFile string
// BlockDotfiles skips files whose path components start with ".".
BlockDotfiles bool
// CompressEnabled enables pre-compression of loaded files.
CompressEnabled bool
// CompressMinSize is the minimum file size for compression.
CompressMinSize int
// CompressLevel is the gzip compression level.
CompressLevel int
// CompressFn is an optional function that gzip-compresses src.
// When nil, no gzip variants are produced.
CompressFn func(src []byte, level int) ([]byte, error)
// Header config for pre-computing Cache-Control at preload time (PERF-003).
HTMLMaxAge int
StaticMaxAge int
ImmutablePattern string
}
PreloadConfig controls preload behaviour. It mirrors the subset of the full config that the preload step needs, avoiding a circular import with the config package.
type PreloadStats ¶ added in v1.3.0
type PreloadStats struct {
// Files is the number of files successfully loaded into cache.
Files int
// Bytes is the total raw (uncompressed) bytes loaded.
Bytes int64
// Skipped is the number of files skipped (too large, unreadable, etc.).
Skipped int
// Paths is the list of URL keys that were loaded into cache, for pre-warming
// downstream caches (e.g. security.PathCache).
Paths []string
}
PreloadStats holds the results of a cache preload operation.