1
Home
Virgil edited this page 2026-03-11 12:08:00 +00:00
Table of Contents
go-cache
Module: forge.lthn.ai/core/go-cache
File-based cache with TTL expiry and path traversal protection. Stores JSON entries with metadata (cached_at, expires_at) as individual files. Designed for caching GitHub API responses but usable for any JSON-serialisable data.
Architecture
Single file: cache.go. Each cache key maps to a .json file in the cache directory.
Key Types
Cache
Cache— File-based cache:Get(),Set(),Delete(),Clear(),Age(),Path()Entry— Stored item:Data json.RawMessage,CachedAt time.Time,ExpiresAt time.Time
Constants
DefaultTTL= 1 hour
GitHub Key Helpers
GitHubReposKey(org)— Key for org repo list:github/{org}/reposGitHubRepoKey(org, repo)— Key for repo metadata:github/{org}/{repo}/meta
Operations
| Method | Description |
|---|---|
New(medium, baseDir, ttl) |
Create cache. nil medium defaults to io.Local. Empty baseDir defaults to .core/cache. Zero TTL defaults to 1 hour. |
Get(key, dest) |
Retrieve if exists and not expired. Returns (found bool, err). |
Set(key, data) |
Store with current timestamp + TTL |
Delete(key) |
Remove single entry (no error if missing) |
Clear() |
Remove entire cache directory |
Age(key) |
Time since item was cached (-1 if not found) |
Path(key) |
Full filesystem path for key. Returns error on path traversal attempt. |
Security
Path() validates that the resolved path stays within baseDir to prevent directory traversal attacks via crafted cache keys.
Usage
import "forge.lthn.ai/core/go-cache"
c, _ := cache.New(nil, "", 30*time.Minute)
// Store
c.Set("github/myorg/repos", repoList)
// Retrieve
var repos []Repo
found, _ := c.Get("github/myorg/repos", &repos)
if !found {
// Cache miss — fetch from API
}
// Check age
age := c.Age("github/myorg/repos")
Dependencies
forge.lthn.ai/core/go-io— File I/O abstraction (Mediuminterface)