cache

package
v2.1.5 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Component cache stores

A cached component stores its rendered HTML. By default each component gets its own TTL store. Use h.Cached for output shared by all requests and h.CachedPerKeyT for output that varies by user, tenant, locale, or another input. Include every input that changes the output in the key.

Bound the number of entries

This component caches up to 1,000 profiles for 15 minutes each. Construct it once at startup, reuse the returned function across requests, and close the store when the application shuts down.

package profiles

import (
	"time"

	"github.com/franchb/htmgo/framework/v2/h"
	"github.com/franchb/htmgo/framework/v2/h/cache"
)

func NewProfiles() (profile func(int) *h.Element, closeStore func()) {
	store := cache.NewLRUStore[any, string](1_000)
	profile = h.CachedPerKeyT(15*time.Minute,
		func(id int) (int, h.GetElementFunc) {
			return id, func() *h.Element {
				return h.P(h.TextF("Profile %d", id))
			}
		},
		h.WithCacheStore(store),
	)
	return profile, store.Close
}

The high-level helpers accept a cache.Store[any, string] because they store rendered HTML. Give each component a separate store or an isolated backend namespace. Two components using the same key in a shared store can return each other's HTML.

Configure the default

h.Cached and h.CachedPerKeyT capture their store when the component is constructed. A provider assigned in init() applies to components constructed afterward. Package-level variables in that package have already been initialized. For package-level components that require a limit, pass h.WithCacheStore directly.

To set an application default, assign the provider at startup before constructing components or serving requests. Return a fresh store for each component.

h.DefaultCacheProvider = func() cache.Store[any, string] {
	return cache.NewLRUStore[any, string](10_000)
}

Implement a store

The Store interface specifies six methods:

type Store[K comparable, V any] interface {
	Set(key K, value V, ttl time.Duration)
	Get(key K) (V, bool)
	GetOrCompute(key K, compute func() V, ttl time.Duration) V
	Delete(key K)
	Purge()
	Close()
}

Get reports a miss for absent or expired entries. Concurrent calls to GetOrCompute for the same missing key must share one computation and return its result. A separate lookup followed by an unconditional write allows concurrent callers to repeat the work. Set and GetOrCompute receive the TTL for that entry. Close releases resources owned by the store.

  • The TTL store expires entries by time and periodically removes them. NewTTLStoreWithMaxSize also caps the entry count and evicts the earliest expiration when full.
  • The LRU store enforces an entry limit using recency and checks TTL on lookup.
  • When adapting Redis or Memcached, namespace keys by component, preserve per-entry expiration, and define how concurrent fills coordinate across application instances. For a two-tier cache, promoting an entry to the local tier must preserve its remaining lifetime.

Runnable examples cover bounded per-key caching, changing the default, and wiring a mock distributed backend. Run them from the framework module with go test ./h/cache -run '^Example'.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LRUStore

type LRUStore[K comparable, V any] struct {
	// contains filtered or unexported fields
}

LRUStore is an example of a memory-bounded cache implementation using the Least Recently Used (LRU) eviction policy. This demonstrates how to create a custom cache store that prevents unbounded memory growth.

This is a simple example implementation. For production use, consider using optimized libraries like github.com/elastic/go-freelru or github.com/Yiling-J/theine-go.

func (*LRUStore[K, V]) Close

func (s *LRUStore[K, V]) Close()

Close stops the background cleanup goroutine.

func (*LRUStore[K, V]) Delete

func (s *LRUStore[K, V]) Delete(key K)

Delete removes an entry from the cache.

func (*LRUStore[K, V]) Get

func (s *LRUStore[K, V]) Get(key K) (V, bool)

Get retrieves a value from the cache. Returns the value and true if found and not expired, or the zero value and false otherwise. Marks the entry as recently used.

func (*LRUStore[K, V]) GetOrCompute

func (s *LRUStore[K, V]) GetOrCompute(key K, compute func() V, ttl time.Duration) V

GetOrCompute atomically gets an existing value or computes and stores a new value.

func (*LRUStore[K, V]) Purge

func (s *LRUStore[K, V]) Purge()

Purge removes all items from the cache.

func (*LRUStore[K, V]) Set

func (s *LRUStore[K, V]) Set(key K, value V, ttl time.Duration)

Set adds or updates an entry in the cache with the given TTL. If the cache is at capacity, the least recently used item is evicted.

type Store

type Store[K comparable, V any] interface {
	// Set adds or updates an entry in the cache. The implementation should handle the TTL.
	Set(key K, value V, ttl time.Duration)

	// Get retrieves a value from the cache. Returns the value and true if found and not expired,
	// or the zero value and false otherwise.
	Get(key K) (V, bool)

	// GetOrCompute atomically gets an existing value or computes and stores a new value.
	// This method prevents duplicate computation when multiple goroutines request the same key.
	// The compute function is called only if the key is not found or has expired.
	GetOrCompute(key K, compute func() V, ttl time.Duration) V

	// Delete removes an entry from the cache.
	Delete(key K)

	// Purge removes all items from the cache.
	Purge()

	// Close releases any resources used by the cache, such as background goroutines.
	Close()
}

Store defines the interface for a pluggable cache. This allows users to provide their own caching implementations, such as LRU, LFU, or even distributed caches. The cache implementation is responsible for handling its own eviction policies (TTL, size limits, etc.).

func NewLRUStore

func NewLRUStore[K comparable, V any](maxSize int) Store[K, V]

NewLRUStore creates a new LRU cache with the specified maximum size. When the cache reaches maxSize, the least recently used items are evicted.

func NewTTLStore

func NewTTLStore[K comparable, V any]() Store[K, V]

NewTTLStore creates a new TTL-based cache store with a default 1-minute cleaner interval.

func NewTTLStoreWithInterval

func NewTTLStoreWithInterval[K comparable, V any](cleanInterval time.Duration) Store[K, V]

NewTTLStoreWithInterval creates a new TTL-based cache store with a configurable cleaner interval.

func NewTTLStoreWithMaxSize

func NewTTLStoreWithMaxSize[K comparable, V any](maxSize int) Store[K, V]

NewTTLStoreWithMaxSize creates a new TTL-based cache store with a maximum number of entries. When the cache exceeds maxSize during Set or GetOrCompute, the oldest entries are evicted. Note: eviction is O(n) per insertion that exceeds maxSize. For large caches where eviction performance matters, use LRUStore instead. A maxSize of 0 or less means unlimited.

type TTLStore

type TTLStore[K comparable, V any] struct {
	// contains filtered or unexported fields
}

TTLStore is a time-to-live based cache implementation that mimics the original htmgo caching behavior. It stores values with expiration times and periodically cleans up expired entries.

func (*TTLStore[K, V]) Close

func (s *TTLStore[K, V]) Close()

Close stops the background cleaner goroutine.

func (*TTLStore[K, V]) Delete

func (s *TTLStore[K, V]) Delete(key K)

Delete removes an entry from the cache.

func (*TTLStore[K, V]) Get

func (s *TTLStore[K, V]) Get(key K) (V, bool)

Get retrieves a value from the cache. Returns the value and true if found and not expired, or the zero value and false otherwise.

func (*TTLStore[K, V]) GetOrCompute

func (s *TTLStore[K, V]) GetOrCompute(key K, compute func() V, ttl time.Duration) V

GetOrCompute gets an existing value or computes and stores a new value. Uses per-key deduplication so that concurrent requests for the same key only trigger a single computation, without blocking operations on other keys.

func (*TTLStore[K, V]) Purge

func (s *TTLStore[K, V]) Purge()

Purge removes all items from the cache.

func (*TTLStore[K, V]) Set

func (s *TTLStore[K, V]) Set(key K, value V, ttl time.Duration)

Set adds or updates an entry in the cache with the given TTL.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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