Key-Value Storage (KVS)¶
The KVS package provides a simple, unified interface for key-value storage with support for TTL and listing operations.
Interface¶
// Store is the basic key-value interface.
type Store interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Delete(ctx context.Context, key string) error
Close() error
}
// ListableStore extends Store with key listing.
type ListableStore interface {
Store
List(ctx context.Context, prefix string) ([]string, error)
}
Backends¶
Redis¶
import kvsredis "github.com/plexusone/omnistorage-core/kvs/backend/redis"
store, err := kvsredis.New(kvsredis.Config{
URL: "redis://localhost:6379",
KeyPrefix: "myapp:",
})
if err != nil {
return err
}
defer store.Close()
// Set with 1 hour TTL
err = store.Set(ctx, "user:123", []byte(`{"name":"john"}`), time.Hour)
// Get
data, err := store.Get(ctx, "user:123")
// List keys with prefix
keys, err := store.List(ctx, "user:")
Configuration:
type Config struct {
// URL is the Redis connection URL.
// Format: redis://[user:password@]host:port[/db]
URL string
// KeyPrefix is prepended to all keys.
KeyPrefix string
// PoolSize is the maximum number of connections.
// Default: 10 * GOMAXPROCS
PoolSize int
// ConnectTimeout is the connection timeout.
// Default: 5 seconds
ConnectTimeout time.Duration
// AllowInsecure permits a non-loopback connection without TLS,
// without a password, or with skip_verify. Default: false
AllowInsecure bool
}
Connection security:
New refuses to connect to a Redis server on a non-loopback address unless
the URL uses TLS (rediss://) with certificate verification and includes a
password, and returns an error wrapping kvsredis.ErrInsecureConnection
otherwise. Loopback addresses (localhost, 127.0.0.0/8, ::1) and Unix
sockets (unix://) are always allowed, so local development is unchanged.
// Remote server: TLS and credentials required
store, err := kvsredis.New(kvsredis.Config{
URL: "rediss://app:" + password + "@cache.internal:6380/0",
})
// Trusted private network without TLS or AUTH: opt in explicitly
store, err := kvsredis.New(kvsredis.Config{
URL: "redis://cache.internal:6379",
AllowInsecure: true,
})
Set AllowInsecure only when the network path to Redis is trusted. Without
TLS, everything stored, including session data and tokens, crosses the
network in plaintext.
Use Cases¶
| Use Case | Example |
|---|---|
| Session storage | session/backend/kvs uses KVS for sessions |
| Caching | Cache API responses with TTL |
| Rate limiting | Store request counts with sliding window |
| Feature flags | Store configuration that updates without restart |
| OAuth state | Store OAuth state parameters during flow |
TTL Handling¶
- Pass
0for no expiration - Redis uses native
EXPIREcommands - Memory backend tracks expiration manually
// No expiration
store.Set(ctx, "permanent", data, 0)
// 5 minute TTL
store.Set(ctx, "temp", data, 5*time.Minute)