Documentation menu

Creating Custom Cache Stores

Each cached component stores rendered HTML. The default TTL store removes expired entries in the background. Use a bounded LRU store when many different keys can arrive during a single TTL.

Bound a component's cache

Construct this component once at startup. Keep the returned profile function for request handlers and call the cleanup function when the application shuts down.

Copy
 1package profiles
 2
 3import (
 4	"time"
 5
 6	"github.com/franchb/htmgo/framework/v2/h"
 7	"github.com/franchb/htmgo/framework/v2/h/cache"
 8)
 9
10func NewProfiles() (profile func(int) *h.Element, closeStore func()) {
11	store := cache.NewLRUStore[any, string](1_000)
12	profile = h.CachedPerKeyT(15*time.Minute,
13		func(id int) (int, h.GetElementFunc) {
14			return id, func() *h.Element {
15				return h.P(h.TextF("Profile %d", id))
16			}
17		},
18		h.WithCacheStore(store),
19	)
20	return profile, store.Close
21}

Use a separate store for each component. For user-specific output, include the user and every other input that changes the rendered HTML in the key.

Set an application default

Assign the provider before constructing components or serving requests. Each call creates a separate store. Existing components keep their original store, including package-level components initialized before init() runs.

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

Implement a store

Copy
1type Store[K comparable, V any] interface {
2	Set(key K, value V, ttl time.Duration)
3	Get(key K) (V, bool)
4	GetOrCompute(key K, compute func() V, ttl time.Duration) V
5	Delete(key K)
6	Purge()
7	Close()
8}

Get reports a miss for absent or expired entries. GetOrCompute must coordinate concurrent misses for a key so that its callers share one computation. Both Set and GetOrCompute take a per-entry TTL. Close releases resources owned by the store.

The component helpers take a Store[any, string]. For a Redis or Memcached backend, give each component its own key namespace, preserve expiration, and coordinate concurrent fills across instances. A local cache in front of a remote one must preserve the remaining TTL when promoting entries.

Cache implementations and runnable examples