ezcache

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2025 License: MIT Imports: 3 Imported by: 0

README

ezcache

ezcache is a simple in-memory cache for golang that has data expiry.

Usage

import "codeberg.org/danjones000/ezcache"

// ...

// Create a user cache which will cache users for five minutes
userCache := ezcache.New(func(id uint64) (User, error) {
    // logic to fetch user from database
    return User{}, nil
}, 5 * time.Minute)

user, err := user.Get(userID)
// Next time you do user.Get with the same userID within five minutes, it will be fetched from cache.
// After five minutes, it will fetch from the database again.

Documentation

Overview

Example
package main

import (
	"fmt"
	"time"

	"codeberg.org/danjones000/ezcache"
)

func main() {
	// Create a five minute cache.
	cache, _ := ezcache.New(func(id uint8) (string, error) {
		fmt.Println("Fetching new value for", id)
		return fmt.Sprintf("%d", id), nil
	}, 5*time.Minute)

	val, _ := cache.Get(5)
	fmt.Println("Got value", val)
	val, _ = cache.Get(5)
	fmt.Println("Got value", val)
	val, _ = cache.Get(4)
	fmt.Println("Got value", val)

}
Output:

Fetching new value for 5
Got value 5
Got value 5
Fetching new value for 4
Got value 4

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidExpiry = errors.New("invalid duration")

ErrInvalidExpiry is returned by Cache.SetExpiry if the duration is invalid. This is usually if it is <= 0.

View Source
var ErrInvalidFetcher = errors.New("invalid fetcher")

ErrInvalidFetcher is returned by Cache.SetFetcher if the fetcher is invalid. This is probably only going to happen if it's nil.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] interface {
	// Get will fetch the value for key. If in the cache, it will fetch the cached value.
	// If not in the cache, it will use the Fetcher.
	// It may return [ErrInvalidFetcher], but if an error is returned, it's probably returned by the
	// [Fetcher] itself.
	Get(key K) (V, error)

	// SetFetcher sets the fetcher for this [Cache].
	SetFetcher(f Fetcher[K, V]) error

	// SetExpiry sets the expiry for this [Cache].
	SetExpiry(d time.Duration) error
}

Cache represents a Cache for values.

func New

func New[K comparable, V any](fetcher Fetcher[K, V], exp time.Duration) (Cache[K, V], error)

type Fetcher

type Fetcher[K comparable, V any] func(K) (V, error)

Jump to

Keyboard shortcuts

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