cache

package
v2.349.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package cache provides cache abstractions, configuration, and drivers for go-service.

The primary entrypoint is `NewCache`, which constructs a `*Cache` from configuration and registers lifecycle hooks to flush/close the underlying cache driver on shutdown.

Disabled / nil behavior

Caching is intentionally optional. When cache configuration is disabled/unset, constructors return nil and callers are expected to tolerate a nil cache instance.

In addition to the instance API on `*Cache`, this package exposes package-level generic helpers (`Get` and `Persist`). Those helpers are nil-safe after `Register` has been called (via DI wiring in `Module`), and they become no-ops / return zero values when caching is disabled. In the standard service composition this registration is performed for you by the module graph.

Value encoding

`Cache` persists arbitrary values by encoding (and optionally compressing) them before passing them to the configured driver. The encoder/compressor used is selected by configuration with sensible defaults.

TTL resolution

TTL handling depends on the selected driver. In particular, the built-in in-memory `sync` driver comes from an upstream dependency and currently tracks expiry at whole-second resolution. Sub-second TTLs may therefore be rounded in driver-specific ways and should not be relied on with that backend.

Index

Constants

This section is empty.

Variables

Module wires the cache subsystem into Fx.

It provides, in order:

  • a cache Driver (see cache/driver.NewDriver)
  • a *Cache (see NewCache)
  • package-level registration (see Register) so generic helpers (Get/Persist) can be used

Disabled behavior

When caching is disabled via configuration, driver.NewDriver returns a nil Driver and NewCache returns a nil *Cache. Register is still invoked with nil, which makes the package-level helpers behave as if caching is disabled (no-ops / zero values) rather than failing.

Functions

func Get

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

Get loads a cached value for key into a newly allocated value of type T and returns it.

Semantics:

  • If caching is disabled (no cache registered), Get returns a zero-value *T and a nil error.
  • If the cache driver reports a miss/expired entry, Get returns a zero-value *T and a nil error.
  • If a non-miss error occurs (for example decode failure or driver error), Get returns the zero-value *T along with that error.

The returned pointer is always non-nil.

func Persist

func Persist[T any](ctx context.Context, key string, value *T, ttl time.Duration) error

Persist stores value under key with the provided TTL.

If caching is disabled (no cache registered), Persist is a no-op and returns nil. Otherwise it delegates to the registered `*Cache`.

func Register

func Register(c *Cache)

Register installs the package-level cache instance used by the generic helper functions.

This function is primarily intended to be called by dependency injection wiring (see `Module`). Once registered, package-level helpers like `Get` and `Persist` will delegate to the registered `*Cache` instance.

If c is nil, the helpers behave as if caching is disabled (they return zero values / act as no-ops).

Types

type Cache

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

Cache provides a typed-ish cache facade on top of a cache driver.

It serializes values using an encoder, optionally compresses the serialized bytes, base64-encodes the final bytes, and stores the resulting string via the configured driver.

Encoding selection is operation-dependent:

  • Persist uses "plain" only for io.WriterTo values
  • Get uses "plain" only for io.ReaderFrom destinations
  • proto.Message uses "proto"
  • otherwise the configured encoder is used, falling back to "json"

Compression is selected from configuration, falling back to "none" when unknown/unavailable.

func NewCache

func NewCache(params CacheParams) *Cache

NewCache constructs a Cache from configuration and registers a shutdown hook.

If caching is disabled (i.e. params.Config is nil), NewCache returns nil. Callers are expected to tolerate a nil cache instance.

When enabled, NewCache registers an OnStop lifecycle hook that calls (*Cache).Close to flush the underlying driver on shutdown.

func (*Cache) Close

func (c *Cache) Close(_ context.Context) error

Close flushes the underlying driver.

This is typically invoked automatically via the lifecycle hook registered by NewCache.

func (*Cache) Get

func (c *Cache) Get(_ context.Context, key string, value any) error

Get loads a cached value for key into value.

Cache misses are not treated as errors: if the entry is missing or expired, Get returns nil and leaves value unchanged.

The value parameter should be a pointer to the destination value (for example *MyStruct).

func (*Cache) Persist

func (c *Cache) Persist(_ context.Context, key string, value any, ttl time.Duration) error

Persist stores value under key with the provided TTL.

The value is encoded, compressed, and base64-encoded before being saved via the driver. A TTL <= 0 is passed through to the driver; semantics are driver-specific (for example, it may mean "no expiration" or "immediate expiration").

TTL resolution is also driver-specific. The built-in in-memory `sync` driver provided by the vendored cachego dependency uses whole-second expiry tracking, so sub-second TTLs should not be relied on with that backend.

func (*Cache) Remove

func (c *Cache) Remove(_ context.Context, key string) error

Remove deletes a cached key.

If the key does not exist, driver behavior is implementation-specific.

type CacheParams added in v2.50.0

type CacheParams struct {
	di.In
	Lifecycle  di.Lifecycle
	Config     *config.Config
	Encoder    *encoding.Map
	Pool       *sync.BufferPool
	Compressor *compress.Map
	Driver     driver.Driver
}

CacheParams defines dependencies for constructing a Cache.

It is intended for dependency injection (Fx/Dig). The constructor will typically be wired via `Module`.

Directories

Path Synopsis
Package config provides cache configuration types for go-service.
Package config provides cache configuration types for go-service.
Package driver provides cache driver construction and related helpers for go-service.
Package driver provides cache driver construction and related helpers for go-service.
Package telemetry exposes selected Redis OpenTelemetry helpers through the go-service cache import tree.
Package telemetry exposes selected Redis OpenTelemetry helpers through the go-service cache import tree.

Jump to

Keyboard shortcuts

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