A lightweight, generic, thread-safe in-memory key-value cache for Go with TTL-based expiration and automatic background cleanup.
- Generic -- store any value type via Go generics
- Thread-safe -- all operations are protected by a
sync.RWMutex - TTL expiration -- default TTL per cache, per-item override with
PutWithTTL - Automatic cleanup -- background goroutine periodically removes expired entries
- Lazy expiration --
Get,Pop,Has,Len, andKeysnever return expired items even between cleanups
go get github.com/leodeim/cof
Requires Go 1.23+.
package main
import (
"fmt"
"time"
"github.com/leodeim/cof"
)
func main() {
c, err := cof.Init[string](
cof.TTL(5 * time.Minute),
cof.CleanInterval(1 * time.Minute),
)
if err != nil {
panic(err)
}
defer c.Stop()
c.Put("greeting", "hello, world!")
v, ok := c.Get("greeting")
fmt.Println(v, ok) // hello, world! true
}c, err := cof.Init[ValueType](opts ...cof.Option)| Option | Default | Description |
|---|---|---|
cof.TTL(d) |
15 min | Default TTL for entries. Pass 0 to disable expiration. |
cof.CleanInterval(d) |
1 min | How often the cleaner runs. Pass 0 to disable background cleanup. |
| Method | Description |
|---|---|
Put(key, value) |
Insert/update with the default TTL |
PutWithTTL(key, value, ttl) |
Insert/update with a custom TTL (0 = no expiry) |
Get(key) (T, bool) |
Retrieve a value; returns false if missing or expired |
Pop(key) (T, bool) |
Retrieve and delete; returns false if missing or expired |
Delete(key) |
Remove an entry |
Has(key) bool |
Check existence (expired entries return false) |
Len() int |
Count of live entries |
Keys() []string |
Sorted slice of live keys |
Clear() |
Remove all entries (keeps the cleaner running) |
Stop() |
Remove all entries and stop the background goroutine |
