cache

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package cache provides HTTP response caching middleware for httpio.

The cache middleware improves performance by storing HTTP responses and serving them from cache for subsequent identical requests. It supports multiple storage backends including in-memory, disk-based, and distributed caching systems.

Index

Constants

This section is empty.

Variables

CacheableStatus defines HTTP status codes that can be cached

Functions

This section is empty.

Types

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (*CachedResponse, bool)
	Set(ctx context.Context, key string, response *CachedResponse) error
	Delete(ctx context.Context, key string) error
	Clear(ctx context.Context) error
	Close() error
}

Cache defines the interface that all cache implementations must satisfy

type CachedResponse

type CachedResponse struct {
	// Response is the HTTP response
	Response *http.Response
	// Body contains the response body bytes
	Body []byte
	// RequestURL is the original request URL
	RequestURL string
	// LastAccessed tracks when this entry was last used
	LastAccessed time.Time
	// CreatedAt tracks when this entry was created
	CreatedAt time.Time
	// ExpiresAt defines when this entry expires
	ExpiresAt time.Time
}

CachedResponse represents a cached HTTP response

type Config

type Config struct {
	// Enabled determines whether caching is enabled
	Enabled bool
	// DefaultTTL is the default time-to-live for cached responses
	DefaultTTL time.Duration
	// RespectCacheControl determines whether to respect Cache-Control headers
	RespectCacheControl bool
	// IncludePatterns is a list of URL patterns to cache (if empty, all URLs are cached)
	IncludePatterns []string
	// ExcludePatterns is a list of URL patterns to exclude from caching
	ExcludePatterns []string
	// ExcludeHosts is a list of hosts to exclude from caching
	ExcludeHosts []string
	// CleanupInterval is the interval at which expired cache entries are cleaned up
	CleanupInterval time.Duration
	// KeyStrategy defines how cache keys are generated
	KeyStrategy KeyStrategyType
	// DomainTTLRules allows specifying different TTLs for different domains
	DomainTTLRules map[string]time.Duration
	// PathTTLRules allows specifying different TTLs for different URL path patterns
	PathTTLRules map[string]time.Duration
}

Config holds configuration options for the cache middleware

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration for the cache middleware

func (*Config) WithCleanupInterval

func (c *Config) WithCleanupInterval(interval time.Duration) *Config

WithCleanupInterval sets the interval for cleaning up expired cache entries

func (*Config) WithDefaultTTL

func (c *Config) WithDefaultTTL(ttl time.Duration) *Config

WithDefaultTTL sets the default time-to-live for cached responses

func (*Config) WithDomainTTL

func (c *Config) WithDomainTTL(domain string, ttl time.Duration) *Config

WithDomainTTL sets a specific TTL for a domain

func (*Config) WithEnabled

func (c *Config) WithEnabled(enabled bool) *Config

WithEnabled sets whether caching is enabled

func (*Config) WithExcludeHosts

func (c *Config) WithExcludeHosts(hosts ...string) *Config

WithExcludeHosts sets hosts to exclude from caching

func (*Config) WithExcludePatterns

func (c *Config) WithExcludePatterns(patterns ...string) *Config

WithExcludePatterns sets URL patterns to exclude from caching

func (*Config) WithIncludePatterns

func (c *Config) WithIncludePatterns(patterns ...string) *Config

WithIncludePatterns sets URL patterns to include in caching

func (*Config) WithKeyStrategy

func (c *Config) WithKeyStrategy(strategy KeyStrategyType) *Config

WithKeyStrategy sets the key generation strategy

func (*Config) WithPathTTL

func (c *Config) WithPathTTL(pathPattern string, ttl time.Duration) *Config

WithPathTTL sets a specific TTL for a URL path pattern

func (*Config) WithRespectCacheControl

func (c *Config) WithRespectCacheControl(respect bool) *Config

WithRespectCacheControl sets whether to respect Cache-Control headers

type DiskCache

type DiskCache struct {
	// contains filtered or unexported fields
}

DiskCache implements the Cache interface using the filesystem for storage

func NewDiskCache

func NewDiskCache(basePath string, maxSizeMB int) (*DiskCache, error)

func (*DiskCache) Clear

func (c *DiskCache) Clear(ctx context.Context) error

func (*DiskCache) Close

func (c *DiskCache) Close() error

Close performs any cleanup needed

func (*DiskCache) Delete

func (c *DiskCache) Delete(ctx context.Context, key string) error

func (*DiskCache) Get

func (c *DiskCache) Get(ctx context.Context, key string) (*CachedResponse, bool)

func (*DiskCache) Set

func (c *DiskCache) Set(ctx context.Context, key string, response *CachedResponse) error

func (*DiskCache) StartCleanupTask

func (c *DiskCache) StartCleanupTask(interval time.Duration)

type FullRequestKeyStrategy

type FullRequestKeyStrategy struct{}

FullRequestKeyStrategy generates keys based on method, URL, headers, and body

func NewFullRequestKeyStrategy

func NewFullRequestKeyStrategy() *FullRequestKeyStrategy

func (*FullRequestKeyStrategy) GenerateKey

func (s *FullRequestKeyStrategy) GenerateKey(req *http.Request) string

type KeyStrategy

type KeyStrategy interface {
	GenerateKey(req *http.Request) string
}

KeyStrategy defines how cache keys are generated from HTTP requests

type KeyStrategyType

type KeyStrategyType int

KeyStrategyType defines the available key generation strategies

const (
	// KeyByURLAndMethod uses URL + HTTP method for cache keys
	KeyByURLAndMethod KeyStrategyType = iota
	// KeyByURLOnly uses only the URL for cache keys
	KeyByURLOnly
	// KeyByFullRequest uses URL + method + headers + body for cache keys
	KeyByFullRequest
)

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache implements the Cache interface using in-memory storage with an LRU eviction policy

func NewMemoryCache

func NewMemoryCache(capacity int) *MemoryCache

func (*MemoryCache) Clear

func (c *MemoryCache) Clear(ctx context.Context) error

func (*MemoryCache) Close

func (c *MemoryCache) Close() error

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(ctx context.Context, key string) error

func (*MemoryCache) Get

func (c *MemoryCache) Get(ctx context.Context, key string) (*CachedResponse, bool)

func (*MemoryCache) Set

func (c *MemoryCache) Set(ctx context.Context, key string, response *CachedResponse) error

func (*MemoryCache) Size

func (c *MemoryCache) Size() int

func (*MemoryCache) StartCleanupTask

func (c *MemoryCache) StartCleanupTask(interval time.Duration)

type MethodURLKeyStrategy

type MethodURLKeyStrategy struct{}

MethodURLKeyStrategy generates keys based on HTTP method + URL

func NewMethodURLKeyStrategy

func NewMethodURLKeyStrategy() *MethodURLKeyStrategy

NewMethodURLKeyStrategy creates a new MethodURLKeyStrategy

func (*MethodURLKeyStrategy) GenerateKey

func (s *MethodURLKeyStrategy) GenerateKey(req *http.Request) string

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware implements the middleware.Middleware interface for HTTP caching

func NewMiddleware

func NewMiddleware(cache Cache, config *Config) *Middleware

NewMiddleware creates a new cache middleware instance with the specified cache and config

func (*Middleware) Handle

Handle implements the middleware.Middleware interface

type URLOnlyKeyStrategy

type URLOnlyKeyStrategy struct{}

URLOnlyKeyStrategy generates keys based only on URL

func NewURLOnlyKeyStrategy

func NewURLOnlyKeyStrategy() *URLOnlyKeyStrategy

func (*URLOnlyKeyStrategy) GenerateKey

func (s *URLOnlyKeyStrategy) GenerateKey(req *http.Request) string

Jump to

Keyboard shortcuts

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