cache

package
v1.0.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package cache is a key-value cache with a time to live: a Store (in memory by default), typed helpers, an HTTP response cache interceptor and Wrap to cache a function.

dygo.Module{Imports: []*dygo.Module{cache.Module(cache.Options{TTL: time.Minute})}}

u, err := cache.GetOrSet(ctx, c, "user:"+id, 0, func(ctx context.Context) (*User, error) {
	return s.repo.Find(ctx, id)
})

r.Get("/products", dygo.Handle(c.List), cache.TTL(30*time.Second))
r = r.Use(dygo.Interceptors(dygo.Ref[*cache.Interceptor]()))

Values are stored as JSON, so every store (memory, Redis) behaves the same.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

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

Get decodes the value of key into a T.

func GetOrSet

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

GetOrSet returns the cached value of key, or calls fn, stores its result and returns it. Concurrent callers for the same missing key share one fn call. An error from fn is returned and not cached.

func Key

func Key(k string) dygo.RouteOption

Key sets a fixed cache key for a route, like @CacheKey. By default the key is the request path with its query.

func Module

func Module(o Options) *dygo.Module

Module provides *Cache and the HTTP *Interceptor. It is global; import it once in the root module.

func NoCache

func NoCache() dygo.RouteOption

NoCache turns the interceptor off for a route.

func Set

func Set(ctx context.Context, c *Cache, key string, v any, ttl time.Duration) error

Set stores v as JSON under key. ttl 0 means the default TTL.

func TTL

TTL sets the time to live of a route's cached responses, like @CacheTTL.

func Wrap

func Wrap[K comparable, V any](c *Cache, prefix string, ttl time.Duration, fn func(ctx context.Context, k K) (V, error)) func(ctx context.Context, k K) (V, error)

Wrap returns fn with its results cached under prefix + ":" + the argument (formatted with %v), for ttl (0 is the default TTL). Go cannot implement an interface at runtime, so caching a service means a small decorator that keeps the wrapped functions:

type cachedUsers struct {
	Users
	byID func(context.Context, string) (*User, error)
}

func (u cachedUsers) ByID(ctx context.Context, id string) (*User, error) { return u.byID(ctx, id) }

func NewCachedUsers(u *UserService, c *cache.Cache) Users {
	return cachedUsers{Users: u, byID: cache.Wrap(c, "user", time.Minute, u.ByID)}
}

Types

type Cache

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

Cache reads and writes JSON values in a Store.

func New

func New(o Options) *Cache

New returns a cache.

func (*Cache) Delete

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

Delete removes key.

func (*Cache) GetRaw

func (c *Cache) GetRaw(ctx context.Context, key string) ([]byte, bool, error)

GetRaw returns the stored bytes of key.

func (*Cache) SetRaw

func (c *Cache) SetRaw(ctx context.Context, key string, val []byte, ttl time.Duration) error

SetRaw stores bytes under key. ttl 0 means the default TTL.

func (*Cache) TTL

func (c *Cache) TTL() time.Duration

TTL is the default time to live.

type Interceptor

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

Interceptor caches the results of GET routes. It caches JSON results, strings and byte slices, not Responders (streams, files, SSE) or NoContent; headers set by the handler are not cached. Other methods and transports pass through. A JSON result is encoded once: the interceptor returns it as dygo.RawJSON, on a hit and on a miss, so interceptors outside it see the encoded bytes.

func NewInterceptor

func NewInterceptor(c *Cache) *Interceptor

NewInterceptor returns the interceptor for c.

func (*Interceptor) Intercept

func (i *Interceptor) Intercept(ec dygo.ExecutionContext, next dygo.CallHandler) (any, error)

Intercept implements dygo.Interceptor.

type Memory

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

Memory is an in-process Store that keeps at most a fixed number of entries and evicts the least recently used one when full. Expired entries are removed when read or evicted.

func NewMemory

func NewMemory(size int) *Memory

NewMemory returns a memory store for up to size entries (at least 1).

func (*Memory) Delete

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

Delete implements Store.

func (*Memory) Get

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

Get implements Store. The returned slice must not be modified.

func (*Memory) Len

func (m *Memory) Len() int

Len returns the number of entries, including expired ones not yet removed.

func (*Memory) Set

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

Set implements Store. ttl 0 means no expiry.

type Options

type Options struct {
	// Store holds the values. The default is NewMemory(10_000).
	Store Store
	// TTL is the default time to live; 0 means entries do not expire.
	TTL time.Duration
	// Prefix is put in front of every key, so apps can share a store.
	Prefix string
}

Options configures Module and New.

type Store

type Store interface {
	Get(ctx context.Context, key string) (val []byte, ok bool, err error)
	Set(ctx context.Context, key string, val []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
}

Store keeps raw values. Implementations must be safe for concurrent use. Get returns ok false for a missing or expired key.

Jump to

Keyboard shortcuts

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