xcache

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 8 Imported by: 0

README

go-xcache

Go Reference Go Report Card Test

A generic, file-based, TTL-aware cache for Go CLI tools. Stores any struct under $XDG_CACHE_HOME with per-entry TTL, pluggable serialization, and configurable key encoding.

Install

go get github.com/jackchuka/go-xcache

Usage

import "github.com/jackchuka/go-xcache"

// Create a typed cache
releases := xcache.New[Release]("my-tool",
    xcache.WithNamespace("releases"),
    xcache.WithDefaultTTL(24 * time.Hour),
)

// Get / Set
releases.Set("owner/repo", release, 24*time.Hour)
val, ok := releases.Get("owner/repo")

// Fetch-through pattern
val, err := releases.GetOrSet("owner/repo", 0, func() (Release, error) {
    return client.GetLatestRelease(owner, repo)
})

// Cleanup
releases.Delete("owner/repo")
releases.Clear()

API

Method Description
New[V](toolName, ...Option) Create a cache. Panics on invalid inputs.
Get(key) Returns (value, true) on hit, (zero, false) on miss/expired/error.
Set(key, value, ttl) Stores a value. Returns error on disk failure.
GetOrSet(key, ttl, fn) Returns cached value or calls fn, caches result.
Delete(key) Removes an entry.
Clear() Removes all entries in this cache's namespace.

Options

xcache.WithNamespace("releases")      // subdirectory under tool cache
xcache.WithDefaultTTL(time.Hour)      // fallback when Set gets ttl=0
xcache.WithCodec(myCodec)             // default: JSON
xcache.WithKeyFunc(xcache.SafeNameKeyFunc) // default: SHA-256 hash

On-Disk Layout

~/.cache/
  my-tool/
    releases/
      a1b2c3d4e5f6...json    # SHA-256 of key

Each file:

{
  "key": "owner/repo",
  "expires_at": "2026-03-15T14:30:00Z",
  "value": { "tag": "v1.2.3" }
}

Key Functions

  • SHA256KeyFunc (default) -- safe, fixed-length, not human-readable
  • SafeNameKeyFunc -- replaces /\:*?"<>| with _, readable filenames. Falls back to SHA-256 for keys >200 chars.

Custom Codec

Implement the Codec interface:

type Codec interface {
    Marshal(v any) ([]byte, error)
    Unmarshal(data []byte, v any) error
    Extension() string // e.g. ".json", ".gob"
}

Design

  • One file per key -- no locking, safe for concurrent goroutines
  • Atomic writes -- temp file + os.Rename
  • Lazy expiry -- expired files deleted on Get, no background cleanup
  • XDG compliant -- respects $XDG_CACHE_HOME via adrg/xdg
  • Get never fails -- returns (zero, false) on any error
  • Set returns errors -- caller decides whether to handle

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SHA256KeyFunc

func SHA256KeyFunc(key string) string

SHA256KeyFunc hashes the key with SHA-256, producing a 64-char hex string.

func SafeNameKeyFunc

func SafeNameKeyFunc(key string) string

SafeNameKeyFunc replaces filename-unsafe characters with underscores. Falls back to SHA256KeyFunc for keys longer than 200 characters.

Types

type Cache

type Cache[V any] struct {
	// contains filtered or unexported fields
}

Cache is a generic, file-based, TTL-aware cache.

func New

func New[V any](toolName string, opts ...Option) *Cache[V]

New creates a cache instance. Panics if toolName, namespace, or options are invalid.

func (*Cache[V]) Clear

func (c *Cache[V]) Clear() error

Clear removes all files in this cache's directory. Only removes files, not subdirectories (which may be other namespaces).

func (*Cache[V]) Delete

func (c *Cache[V]) Delete(key string) error

Delete removes a single cache entry. Returns nil if the entry does not exist.

func (*Cache[V]) Get

func (c *Cache[V]) Get(key string) (V, bool)

Get returns the cached value. Returns (zero, false) if missing, expired, or unreadable. Expired entries are lazily deleted from disk.

func (*Cache[V]) GetOrSet

func (c *Cache[V]) GetOrSet(key string, ttl time.Duration, fn func() (V, error)) (V, error)

GetOrSet returns the cached value if present, otherwise calls fn to fetch it, caches the result, and returns it. If fn succeeds but Set fails, the value is still returned alongside the Set error.

func (*Cache[V]) Set

func (c *Cache[V]) Set(key string, value V, ttl time.Duration) error

Set stores a value with the given TTL. Uses default TTL if ttl is 0.

type Codec

type Codec interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
	Extension() string // must include leading dot: ".json", ".gob", etc.
}

Codec defines how cache entries are serialized and deserialized.

type JSONCodec

type JSONCodec struct{}

JSONCodec serializes entries as indented JSON.

func (JSONCodec) Extension

func (JSONCodec) Extension() string

func (JSONCodec) Marshal

func (JSONCodec) Marshal(v any) ([]byte, error)

func (JSONCodec) Unmarshal

func (JSONCodec) Unmarshal(data []byte, v any) error

type KeyFunc

type KeyFunc func(key string) string

KeyFunc transforms a cache key into a filename-safe string.

type Option

type Option func(*config)

Option configures a Cache instance.

func WithCodec

func WithCodec(codec Codec) Option

WithCodec sets the serialization codec. Default is JSONCodec.

func WithDefaultTTL

func WithDefaultTTL(d time.Duration) Option

WithDefaultTTL sets the fallback TTL used when Set is called with ttl=0.

func WithKeyFunc

func WithKeyFunc(fn KeyFunc) Option

WithKeyFunc sets the key-to-filename function. Default is SHA256KeyFunc.

func WithNamespace

func WithNamespace(ns string) Option

WithNamespace sets the subdirectory within the tool's cache directory.

Jump to

Keyboard shortcuts

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