Cache
core.ICache — Redis wrapper. ctx.Cache() returns a handle bound to the request context, so methods take no ctx. JSON helpers are generic and type-safe.
Connect & wire
go
redis, err := core.NewCache(env) // uses CACHE_* / CACHE_CONNECTION_STRING
app, _ := core.NewApp(env, core.WithCache("default", redis))See env.md for connection-string vs discrete fields.
Basic operations
go
c := ctx.Cache()
c.Set("user:1", user, time.Minute) // structs are JSON-encoded
c.Set("token", "abc", time.Hour) // string/[]byte stored raw
var u User
err := c.Get("user:1", &u) // JSON-decoded into u
if errors.Is(err, core.ErrCacheMiss) {
// key absent
}
ok, _ := c.Exists("user:1")
c.Del("user:1", "token")Type-safe JSON helpers
go
user, err := core.GetJSON[User](ctx.Cache(), "user:1")
err = core.SetJSON(ctx.Cache(), "user:1", user, time.Minute)Cache-aside (Remember)
Return the cached value, or compute + cache it on a miss:
go
user, err := core.Remember(ctx.Cache(), "user:1", time.Minute, func() (User, error) {
return repository.New[User](ctx).FindOne("id = ?", 1)
})Interface
go
type ICache interface {
Get(key string, dest any) IError
Set(key string, value any, ttl time.Duration) IError
Del(keys ...string) IError
Exists(key string) (bool, IError)
WithContext(ctx context.Context) ICache // escape hatch
Redis() redis.UniversalClient // raw client
Close() IError
}Custom context
go
bg, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
core.GetJSON[User](ctx.Cache().WithContext(bg), "user:1")