Skip to content

Repository files navigation

TestsCode ScanningReportReleaseReleases

cof

A lightweight, generic, thread-safe in-memory key-value cache for Go with TTL-based expiration and automatic background cleanup.

Features

  • 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, and Keys never return expired items even between cleanups

Install

go get github.com/leodeim/cof

Requires Go 1.23+.

Quick start

package main
import (
"fmt""time""github.com/leodeim/cof"
)
funcmain() {
c, err:=cof.Init[string](
cof.TTL(5*time.Minute),
cof.CleanInterval(1*time.Minute),
)
iferr!=nil {
panic(err)
}
deferc.Stop()
c.Put("greeting", "hello, world!")
v, ok:=c.Get("greeting")
fmt.Println(v, ok) // hello, world! true
}

API

Creating a cache

c, err:=cof.Init[ValueType](opts...cof.Option)

Options

OptionDefaultDescription
cof.TTL(d)15 minDefault TTL for entries. Pass 0 to disable expiration.
cof.CleanInterval(d)1 minHow often the cleaner runs. Pass 0 to disable background cleanup.

Operations

MethodDescription
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) boolCheck existence (expired entries return false)
Len() intCount of live entries
Keys() []stringSorted slice of live keys
Clear()Remove all entries (keeps the cleaner running)
Stop()Remove all entries and stop the background goroutine

License

MIT

Releases

Used by

Contributors

Languages