memoise

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

View Source
const ContextKeyMemoise = "gohacks/memoise@v1"

Key used to store the instance in the context's user value.

Variables

View Source
var ErrValueNotMemoise = errors.Base("value is not Memoise")

Signalled if the instance associated with the context key is not of type Memoise.

Functions

func InitPrometheus added in v1.0.6

func InitPrometheus(reg prometheus.Registerer)

Initialise Prometheus metrics.

func SetMemoise added in v1.0.6

func SetMemoise(ctx context.Context, inst Memoise) (context.Context, error)

Set Memoise stores the instance in the context map.

func SetMemoiseIfAbsent added in v1.0.6

func SetMemoiseIfAbsent(ctx context.Context, inst Memoise) (context.Context, error)

SetMemoiseIfAbsent sets only if not already present.

func WithMemoise added in v1.0.6

func WithMemoise(ctx context.Context, fn func(Memoise))

WithMemoise calls fn with the instance or fallback.

Types

type CallbackFn

type CallbackFn func() (any, error)

Memoisation function type.

type Config added in v1.0.6

type Config struct {
	// Prometheus registerer.
	Prometheus prometheus.Registerer `json:"-"`

	// Instance name.
	//
	// This gets used for Prometheus metrics should you have more than
	// one memoiser in your application.
	Name string `json:"-"`
}

func NewDefaultConfig added in v1.0.6

func NewDefaultConfig() *Config

type Memoise

type Memoise interface {
	// Check returns the memoised value for the given key if available.
	// Otherwise it calls the provided callback to compute the value,
	// stores the result, and returns it.
	// Thread-safe.
	Check(string, CallbackFn) (any, error)

	// Clear the contents of the memoise map.
	Reset()
}

Memoisation type.

func FromMemoise added in v1.0.6

func FromMemoise(ctx context.Context) Memoise

FromMemoise returns the instance or the fallback.

func GetMemoise added in v1.0.6

func GetMemoise(ctx context.Context) (Memoise, error)

Get the logger from the given context.

Will return ErrValueNotMemoise if the value in the context is not of type Memoise.

func MustGetMemoise added in v1.0.6

func MustGetMemoise(ctx context.Context) Memoise

Attempt to get the instance from the given context. Panics if the operation fails.

func NewDefaultMemoise added in v1.0.6

func NewDefaultMemoise() Memoise

func NewMemoise

func NewMemoise(cfg *Config) Memoise

Create a new memoisation object.

func TryGetMemoise added in v1.0.6

func TryGetMemoise(ctx context.Context) (Memoise, bool)

TryGetMemoise returns the instance and true if present and typed.

Jump to

Keyboard shortcuts

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