filecache

package
v0.7.148 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxAge = 7 * 24 * time.Hour

DefaultMaxAge is how long an entry survives when MaxAge is unset. Keys are content-addressed, so a superseded entry is never read again — it only has to outlive the chance of the caller returning to that exact state.

Variables

This section is empty.

Functions

This section is empty.

Types

type FileCache

type FileCache[T any] struct {
	Dir string
	// MaxAge bounds how long an entry survives after it was written. Zero means
	// DefaultMaxAge. Nothing switches the sweep off: an unbounded cache
	// directory is a leak rather than a feature.
	MaxAge time.Duration
}

FileCache is a generic JSON-on-disk cache keyed by arbitrary strings. Each entry is stored as a single file whose name is the hex-encoded SHA-256 of the raw key string. Concurrent writes to the same key are safe: Put stages the entry in its own temporary file and renames it into place, so a reader sees either the previous entry or a complete new one, never a mixture. Two writers racing on one key both produce valid entries and the last rename wins.

A new key means a new file, and nothing supersedes the entries it replaces, so with content-addressed keys the directory would grow one file per write forever. Put sweeps it; see MaxAge.

func (FileCache[T]) Get

func (c FileCache[T]) Get(key string) (T, bool)

Get returns the cached value for key. Returns the zero value and false on a cache miss or any read/unmarshal error; errors are treated as misses so a corrupt entry never blocks execution.

func (FileCache[T]) Put

func (c FileCache[T]) Put(key string, v T) error

Put writes v to the cache under key, creating Dir and any parent directories as needed. The entry is staged in a temporary file alongside its final path and renamed into place, which is atomic within a single directory. Entries have mode 0600, the mode os.CreateTemp applies and the rename preserves.

Put then sweeps Dir, so the cache is bounded by writes to it rather than by anyone remembering to clean it out.

Jump to

Keyboard shortcuts

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