cachevalue

package
v0.0.0-...-614981e Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2024 License: AGPL-3.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[T any] struct {

	// Once can be used to initialize values for lazy initialization.
	// Should be set before calling Get().
	Once sync.Once
	// contains filtered or unexported fields
}

Cache contains a synchronized value that is considered valid for a specific amount of time. An Update function must be set to provide an updated value when needed.

func New

func New[T any]() *Cache[T]

New allocates a new cached value instance. Tt must be initialized with `.TnitOnce`.

func NewFromFunc

func NewFromFunc[T any](ttl time.Duration, opts Opts, update func(ctx context.Context) (T, error)) *Cache[T]

NewFromFunc allocates a new cached value instance and initializes it with an update function, making it ready for use.

func (*Cache[T]) Get

func (t *Cache[T]) Get() (T, error)

Get will return a cached value or fetch a new one. Tf the Update function returns an error the value is forwarded as is and not cached.

func (*Cache[T]) GetWithCtx

func (t *Cache[T]) GetWithCtx(ctx context.Context) (T, error)

GetWithCtx will return a cached value or fetch a new one. passes a caller context, if caller context cancels nothing is cached. If the Update function returns an error the value is forwarded as is and not cached.

func (*Cache[T]) InitOnce

func (t *Cache[T]) InitOnce(ttl time.Duration, opts Opts, update func(ctx context.Context) (T, error))

InitOnce initializes the cache with a TTL and an update function. It is guaranteed to be called only once.

type Opts

type Opts struct {
	// When set to true, return the last cached value
	// even if updating the value errors out.
	// Returns the last good value AND the error.
	ReturnLastGood bool

	// If NoWait is set, Get() will return the last good value,
	// if TTL has expired but 2x TTL has not yet passed,
	// but will fetch a new value in the background.
	NoWait bool
}

Opts contains options for the cache.

Jump to

Keyboard shortcuts

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