cache

package
v0.1.36 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

cache/cache.go

cache/memory.go

cache/middleware.go

cache/redis.go

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("cache: key not found")
	ErrClosed   = errors.New("cache: cache is closed")
)

Common errors

Functions

func DefaultKeyFunc

func DefaultKeyFunc(r *http.Request) string

DefaultKeyFunc generates a cache key from method, path, and query string.

func GetJSON

func GetJSON[T any](ctx context.Context, c Cache, key string) (T, error)

GetJSON retrieves and unmarshals a JSON value.

func GetOrSet

func GetOrSet(ctx context.Context, c Cache, key string, ttl time.Duration, compute func() ([]byte, error)) ([]byte, error)

GetOrSet retrieves a value, or computes and stores it if not found.

func GetOrSetJSON

func GetOrSetJSON[T any](ctx context.Context, c Cache, key string, ttl time.Duration, compute func() (T, error)) (T, error)

GetOrSetJSON retrieves a JSON value, or computes and stores it if not found.

func HashKeyFunc

func HashKeyFunc(r *http.Request) string

HashKeyFunc generates a hashed cache key (useful for long URLs).

func Middleware

func Middleware(c Cache, cfg MiddlewareConfig) func(http.Handler) http.Handler

Middleware returns HTTP middleware that caches responses.

func PathKeyFunc

func PathKeyFunc(r *http.Request) string

PathKeyFunc generates a cache key from path only (ignores query string).

func SetJSON

func SetJSON(ctx context.Context, c Cache, key string, value any, ttl time.Duration) error

SetJSON marshals and stores a value as JSON.

Types

type Cache

type Cache interface {
	// Get retrieves a value by key.
	// Returns ErrNotFound if the key doesn't exist or has expired.
	Get(ctx context.Context, key string) ([]byte, error)

	// Set stores a value with the given TTL.
	// If ttl is 0, the value never expires.
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

	// Delete removes a key from the cache.
	Delete(ctx context.Context, key string) error

	// Exists checks if a key exists.
	Exists(ctx context.Context, key string) (bool, error)

	// Clear removes all entries from the cache.
	Clear(ctx context.Context) error

	// Close releases any resources held by the cache.
	Close() error
}

Cache defines the interface for cache implementations.

type Memory

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

Memory implements an in-memory cache with TTL support.

func NewMemory

func NewMemory() *Memory

NewMemory creates a new in-memory cache.

func NewMemoryWithConfig

func NewMemoryWithConfig(cfg MemoryConfig) *Memory

NewMemoryWithConfig creates an in-memory cache with custom configuration.

func (*Memory) Clear

func (m *Memory) Clear(ctx context.Context) error

Clear removes all entries from the cache.

func (*Memory) Close

func (m *Memory) Close() error

Close stops the cleanup goroutine and releases resources.

func (*Memory) Delete

func (m *Memory) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*Memory) DeleteMulti

func (m *Memory) DeleteMulti(ctx context.Context, keys []string) error

DeleteMulti removes multiple keys at once.

func (*Memory) Exists

func (m *Memory) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists and is not expired.

func (*Memory) Get

func (m *Memory) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value by key.

func (*Memory) GetMulti

func (m *Memory) GetMulti(ctx context.Context, keys []string) (map[string][]byte, error)

GetMulti retrieves multiple values at once.

func (*Memory) Set

func (m *Memory) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value with the given TTL.

func (*Memory) SetMulti

func (m *Memory) SetMulti(ctx context.Context, items map[string][]byte, ttl time.Duration) error

SetMulti stores multiple values at once.

func (*Memory) Size

func (m *Memory) Size() int

Size returns the number of items in the cache (including expired).

type MemoryConfig

type MemoryConfig struct {
	// CleanupInterval is how often to remove expired items.
	// Default: 1 minute. Set to 0 to disable background cleanup.
	CleanupInterval time.Duration

	// InitialCapacity is the initial map capacity.
	// Default: 100.
	InitialCapacity int
}

MemoryConfig configures the in-memory cache.

func DefaultMemoryConfig

func DefaultMemoryConfig() MemoryConfig

DefaultMemoryConfig returns sensible defaults.

type MiddlewareConfig

type MiddlewareConfig struct {
	// TTL is how long to cache responses. Default: 5 minutes.
	TTL time.Duration

	// KeyFunc generates cache keys from requests.
	// Default: method + path + sorted query string.
	KeyFunc func(r *http.Request) string

	// KeyPrefix is prepended to all cache keys.
	KeyPrefix string

	// Skip returns true to skip caching for a request.
	Skip func(r *http.Request) bool

	// CacheErrors caches non-2xx responses. Default: false.
	CacheErrors bool
}

MiddlewareConfig configures the cache middleware.

type MultiDeleter

type MultiDeleter interface {
	DeleteMulti(ctx context.Context, keys []string) error
}

MultiDeleter supports batch delete operations.

type MultiGetter

type MultiGetter interface {
	GetMulti(ctx context.Context, keys []string) (map[string][]byte, error)
}

MultiGetter supports batch get operations.

type MultiSetter

type MultiSetter interface {
	SetMulti(ctx context.Context, items map[string][]byte, ttl time.Duration) error
}

MultiSetter supports batch set operations.

type Redis

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

Redis implements a Redis-backed cache.

func Connect

func Connect(addr, password string, db int) (*Redis, error)

Connect creates a Redis cache with simple connection parameters.

func NewRedis

func NewRedis(client redis.UniversalClient) *Redis

NewRedis creates a new Redis cache with an existing client.

func NewRedisWithConfig

func NewRedisWithConfig(cfg RedisConfig) (*Redis, error)

NewRedisWithConfig creates a Redis cache with custom configuration.

func (*Redis) Clear

func (r *Redis) Clear(ctx context.Context) error

Clear removes all entries with the key prefix. Warning: Uses SCAN which may be slow on large datasets.

func (*Redis) Client

func (r *Redis) Client() redis.UniversalClient

Client returns the underlying Redis client for advanced operations.

func (*Redis) Close

func (r *Redis) Close() error

Close closes the Redis connection.

func (*Redis) Decr

func (r *Redis) Decr(ctx context.Context, key string) (int64, error)

Decr decrements a numeric value and returns the new value.

func (*Redis) Delete

func (r *Redis) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*Redis) DeleteMulti

func (r *Redis) DeleteMulti(ctx context.Context, keys []string) error

DeleteMulti removes multiple keys at once.

func (*Redis) Exists

func (r *Redis) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists.

func (*Redis) Expire

func (r *Redis) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets a TTL on an existing key.

func (*Redis) Get

func (r *Redis) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value by key.

func (*Redis) GetMulti

func (r *Redis) GetMulti(ctx context.Context, keys []string) (map[string][]byte, error)

GetMulti retrieves multiple values at once.

func (*Redis) GetSet

func (r *Redis) GetSet(ctx context.Context, key string, value []byte) ([]byte, error)

GetSet sets a value and returns the old value.

func (*Redis) Incr

func (r *Redis) Incr(ctx context.Context, key string) (int64, error)

Incr increments a numeric value and returns the new value.

func (*Redis) IncrBy

func (r *Redis) IncrBy(ctx context.Context, key string, delta int64) (int64, error)

IncrBy increments a numeric value by delta and returns the new value.

func (*Redis) Set

func (r *Redis) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores a value with the given TTL.

func (*Redis) SetMulti

func (r *Redis) SetMulti(ctx context.Context, items map[string][]byte, ttl time.Duration) error

SetMulti stores multiple values at once.

func (*Redis) SetNX

func (r *Redis) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error)

SetNX sets a value only if the key doesn't exist. Returns true if the key was set.

func (*Redis) TTL

func (r *Redis) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining TTL for a key. Returns -1 if the key has no TTL, -2 if the key doesn't exist.

type RedisConfig

type RedisConfig struct {
	// Client is an existing Redis client.
	// If provided, other connection options are ignored.
	Client redis.UniversalClient

	// Address is the Redis server address (e.g., "localhost:6379").
	Address string

	// Password for Redis authentication.
	Password string

	// DB is the database number to use.
	DB int

	// KeyPrefix is prepended to all keys.
	KeyPrefix string

	// PoolSize is the maximum number of connections.
	// Default: 10.
	PoolSize int

	// DialTimeout is the timeout for establishing connections.
	// Default: 5 seconds.
	DialTimeout time.Duration

	// ReadTimeout is the timeout for read operations.
	// Default: 3 seconds.
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for write operations.
	// Default: 3 seconds.
	WriteTimeout time.Duration
}

RedisConfig configures the Redis cache.

Jump to

Keyboard shortcuts

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