cago

package module
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2025 License: BSD-3-Clause Imports: 3 Imported by: 0

README

Cago

Tiny, in‑memory, thread‑safe key/value cache for Go with TTL support.

Features

  • Simple API with generics for typed Get/Set
  • Per‑key TTL with background cleanup (janitor)
  • Lazy expiration on read for precision
  • Thread‑safe (RWMutex)

Installation

go get github.com/jasakode/cago/v2

Quick Start

package main

import (
    "fmt"
    "time"

    "github.com/jasakode/cago/v2"
)

func main() {
    // Start the cache with a 1s cleanup interval (default)
    _ = cago.New()
    defer cago.Close()

    // Set a value that expires in 5 seconds
    _ = cago.Set("name", "Cago", 5*time.Second)

    // Typed read
    if v, ok := cago.Get[string]("name"); ok {
        fmt.Println(v)
    }
}

API

type Config struct {
    CleanInterval time.Duration // how often to run cleanup; default 1s
    Timezone      cago.Timezone // reserved, not used by the engine
}

func New(cfg ...cago.Config) error
func Close()

func Set[T any](key string, value T, ttl time.Duration) error // error if key exists and not expired
func Put[T any](key string, value T, ttl time.Duration)       // upsert
func Get[T any](key string) (T, bool)                         // typed read
func Exist(key string) bool                                   // checks non‑expired presence
func Remove(key string) bool                                  // delete
func Clear()                                                  // remove all

Notes:

  • ttl <= 0 means the key never expires.
  • Get[T] requires T to match the concrete type stored by Set/Put.
  • Expiration is enforced on read and by a periodic janitor.

Examples

Set/Put/Get with primitives:

_ = cago.Set("a", 42, 0)            // no expiry
_ = cago.Set("b", 3.14, time.Minute) // expires in 1 minute
cago.Put("a", 99, 0)                 // overwrite regardless of existence

if v, ok := cago.Get[int]("a"); ok {
    fmt.Println(v) // 99
}

Struct values:

type User struct { Name string; Age int }
u := User{"Ada", 30}
_ = cago.Set("user:1", u, 10*time.Second)
if got, ok := cago.Get[User]("user:1"); ok { fmt.Println(got.Name) }

Expiration:

_ = cago.Set("tmp", "x", 100*time.Millisecond)
time.Sleep(150 * time.Millisecond)
if _, ok := cago.Get[string]("tmp"); !ok { /* expired */ }

Cleanup and shutdown:

_ = cago.New(cago.Config{CleanInterval: 500 * time.Millisecond})
defer cago.Close()

Concurrency

All operations are safe for concurrent access. The janitor runs in a single goroutine.

License

BSD-3-Clause

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrKeyExists = errors.New("key already exists")

ErrKeyExists is returned by Set when a key already exists and has not expired.

Functions

func Clear

func Clear()

Clear deletes all keys from the cache.

func Close

func Close()

Close stops the background janitor and clears the global instance.

func Exist

func Exist(key string) bool

Exist returns true if a non‑expired value exists for key.

func Get

func Get[T any](key string) (T, bool)

Get retrieves a typed value by key. It returns the zero value of T and false if the key does not exist or has expired. The type parameter T must match the stored value's concrete type.

func New

func New(conf ...Config) error

New initializes the global cache instance and starts the janitor. Calling New multiple times is safe; only the first call creates the cache.

func Put

func Put[T any](key string, value T, ttl time.Duration)

Put stores or replaces a value for the given key regardless of whether it exists. ttl <= 0 means the key never expires.

func Remove

func Remove(key string) bool

Remove deletes a key and returns true if it was present.

func Set

func Set[T any](key string, value T, ttl time.Duration) error

Set stores a new value for the given key only if the key does not already exist or has expired. If the key exists and is not expired, it returns ErrKeyExists. ttl <= 0 means the key never expires.

Types

type Cago

type Cago struct {
	// contains filtered or unexported fields
}

Cago is a lightweight, in‑memory, thread‑safe key/value cache with TTL support. It runs a background janitor that periodically removes expired entries. All exported methods are safe for concurrent use.

type Config

type Config struct {
	// CleanInterval defines how often the janitor scans for expired keys.
	// Default: 1 second if zero.
	CleanInterval time.Duration

	// Timezone is reserved for future use and kept for compatibility.
	// It does not affect cache behavior.
	Timezone Timezone
}

Config controls cache behavior.

type Entry

type Entry struct {
	Key       string
	Value     any
	ExpiresAt int64 // unix milli; 0 means never expires
	CreatedAt int64 // unix milli
	UpdatedAt int64 // unix milli
}

Entry represents a single cache item. Value holds the stored data, ExpiresAt is a unix timestamp in milliseconds. A zero ExpiresAt means the entry never expires.

type Timezone

type Timezone string

Timezone is a placeholder type for potential future features that may depend on time zones. It is currently unused by the cache engine.

const (
	// Universal
	TimezoneUTC   Timezone = "UTC"   // UTC+00
	TimezoneLocal Timezone = "Local" // host system local timezone

	// Indonesia
	TimezoneWIB  Timezone = "Asia/Jakarta"  // UTC+07
	TimezoneWITA Timezone = "Asia/Makassar" // UTC+08
	TimezoneWIT  Timezone = "Asia/Jayapura" // UTC+09

	// Asia
	TimezoneTokyo     Timezone = "Asia/Tokyo"     // UTC+09
	TimezoneSingapore Timezone = "Asia/Singapore" // UTC+08
	TimezoneBangkok   Timezone = "Asia/Bangkok"   // UTC+07
	TimezoneShanghai  Timezone = "Asia/Shanghai"  // UTC+08
	TimezoneDubai     Timezone = "Asia/Dubai"     // UTC+04

	// Europe
	TimezoneLondon Timezone = "Europe/London" // UTC+00 (DST +01)
	TimezoneBerlin Timezone = "Europe/Berlin" // UTC+01 (DST +02)
	TimezoneParis  Timezone = "Europe/Paris"  // UTC+01 (DST +02)
	TimezoneMoscow Timezone = "Europe/Moscow" // UTC+03

	// America
	TimezoneNewYork    Timezone = "America/New_York"    // UTC-05 (DST -04)
	TimezoneLosAngeles Timezone = "America/Los_Angeles" // UTC-08 (DST -07)
	TimezoneChicago    Timezone = "America/Chicago"     // UTC-06 (DST -05)
	TimezoneSaoPaulo   Timezone = "America/Sao_Paulo"   // UTC-03
	TimezoneMexicoCity Timezone = "America/Mexico_City" // UTC-06 (DST -05)

	// Australia / Pacific
	TimezoneSydney   Timezone = "Australia/Sydney" // UTC+10 (DST +11)
	TimezoneAuckland Timezone = "Pacific/Auckland" // UTC+12 (DST +13)
	TimezoneHonolulu Timezone = "Pacific/Honolulu" // UTC-10
)

Directories

Path Synopsis
src
lib

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL