3.2 KiB
| title | description |
|---|---|
| go-cache | Storage-agnostic caching with TTL expiry via the core/io Medium interface. |
go-cache
go-cache is a lightweight, storage-agnostic caching library for Go. It stores
JSON-serialised entries with automatic TTL expiry and path-traversal protection.
Module path: dappco.re/go/core/cache
Licence: EUPL-1.2
Quick Start
import "dappco.re/go/core/cache"
func main() {
// Create a cache with default settings:
// - storage: local filesystem (io.Local)
// - directory: .core/cache/ in the working directory
// - TTL: 1 hour
c, err := cache.New(nil, "", 0)
if err != nil {
return
}
// Store a value
err = c.Set("user/profile", map[string]string{
"name": "Alice",
"role": "admin",
})
if err != nil {
return
}
// Retrieve it (returns false if missing or expired)
var profile map[string]string
found, err := c.Get("user/profile", &profile)
if err != nil {
return
}
if found {
_ = profile["name"] // Use the cached value.
}
}
Package Layout
| File | Purpose |
|---|---|
cache.go |
Core types (Cache, Entry), CRUD operations, key helpers |
cache_test.go |
Tests covering set/get, expiry, delete, clear, defaults |
go.mod |
Module definition (Go 1.26) |
Dependencies
| Module | Version | Role |
|---|---|---|
dappco.re/go/core |
v0.8.0-alpha.1 |
JSON, path, string, and error helper utilities |
dappco.re/go/core/io |
v0.2.0 |
Storage abstraction (Medium interface) |
The cache package imports only dappco.re/go/core and dappco.re/go/core/io.
The resolved build list also includes transitive dependencies from core/io's
optional storage backends.
Key Concepts
Storage Backends
The cache does not read or write files directly. All I/O goes through the
io.Medium interface defined in core/io. This means the same cache logic works
against:
- Local filesystem (
io.Local) -- the default - SQLite KV store (
store.Mediumfromdappco.re/go/core/io/store) - S3-compatible storage (
dappco.re/go/core/io/s3) - In-memory mock (
io.NewMockMedium()) -- ideal for tests
Pass any Medium implementation as the first argument to cache.New().
TTL and Expiry
Every entry records both cached_at and expires_at timestamps. On Get(),
if the current time is past expires_at, the entry is treated as a cache miss
-- no stale data is ever returned. The default TTL is one hour
(cache.DefaultTTL).
GitHub Cache Keys
The package includes two helper functions that produce consistent cache keys for GitHub API data:
cache.GitHubReposKey("host-uk") // "github/host-uk/repos"
cache.GitHubRepoKey("host-uk", "core") // "github/host-uk/core/meta"
These are convenience helpers used by other packages in the ecosystem to avoid key duplication when caching GitHub responses.