Temporary key-value storage with a single Cache interface and two backends: Redis and in-memory.
go get github.com/fatkulnurk/foundation/cache@v0.3.0type Cache interface {
Set(ctx context.Context, key string, value any, ttlSeconds int) error
Get(ctx context.Context, key string) (string, error)
Delete(ctx context.Context, key string) error
Has(ctx context.Context, key string) (bool, error)
}ttlSeconds <= 0means no expiry (local) / Redis zero TTL semantics as implemented.- Keys are stored as
Prefix + keywhenConfig.Prefixis set. Getreturnscache.ErrNotFoundwhen the key is missing or expired (local).
cfg := &cache.Config{Prefix: "myapp:"}
c := cache.NewLocalCache(cfg)
if lc, ok := c.(*cache.LocalCache); ok {
defer lc.Close() // stops background janitor
}
_ = c.Set(ctx, "user:1", "Ada", 60)
v, err := c.Get(ctx, "user:1")Suitable for tests, single-process apps, and data that must not be shared across instances. Expired keys are removed on access and by a background janitor.
import "github.com/redis/go-redis/v9"
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
c := cache.NewRedisCache(&cache.Config{Prefix: "myapp:"}, rdb)
_ = c.Set(ctx, "user:1", "Ada", 60)Use Redis when multiple processes/servers must share the same cache.
| Field | Env (via LoadConfig) |
Description |
|---|---|---|
Prefix |
CACHE_PREFIX |
Optional key prefix (e.g. myapp:) |
cfg := cache.LoadConfig()| Local | Redis | |
|---|---|---|
| Shared across nodes | No | Yes |
| Extra dependency | None | Redis server |
| Best for | Dev, tests, single instance | Production multi-instance |
- Root README
- Example:
example/main.go