Documentation
¶
Overview ¶
A mostly vibe coded cache to learn about publishing go modules.
Index ¶
- type Cache
- func (c *Cache) Clear()
- func (c *Cache) ClearNamespace(namespace string) int
- func (c *Cache) Delete(key string) bool
- func (c *Cache) DeleteByPattern(pattern string) int
- func (c *Cache) DeleteMultiple(keys []string) int
- func (c *Cache) Export() map[string]any
- func (c *Cache) ExtendTTL(key string, additionalTime time.Duration) bool
- func (c *Cache) ForEach(fn func(key string, value any, expiration time.Time) bool)
- func (c *Cache) GCStats() (before, after runtime.MemStats)
- func (c *Cache) Get(key string) (any, bool)
- func (c *Cache) GetByPattern(pattern string) map[string]any
- func (c *Cache) GetByRegex(pattern string) map[string]any
- func (c *Cache) GetMultiple(keys []string) map[string]any
- func (c *Cache) GetTTL(key string) (time.Duration, bool)
- func (c *Cache) HealthCheck() map[string]any
- func (c *Cache) ItemCount() int
- func (c *Cache) Keys() []string
- func (c *Cache) ListNamespaces() []string
- func (c *Cache) LoadFrom(reader io.Reader) error
- func (c *Cache) LoadFromFile(filename string) error
- func (c *Cache) MemoryUsage() int64
- func (c *Cache) Namespace(name string) *CacheNamespace
- func (c *Cache) Refresh(key string) bool
- func (c *Cache) ResetStats()
- func (c *Cache) SaveTo(writer io.Writer) error
- func (c *Cache) SaveToFile(filename string) error
- func (c *Cache) Set(key string, value any, ttl time.Duration)
- func (c *Cache) SetCallbacks(callbacks *CacheCallbacks)
- func (c *Cache) SetMaxSize(maxSize int)
- func (c *Cache) SetMemoryLimit(limit int64)
- func (c *Cache) SetMultiple(items map[string]any, ttl time.Duration) error
- func (c *Cache) SetWithAbsoluteExpiry(key string, value any, expireAt time.Time)
- func (c *Cache) SetWithNamespace(key string, value any, ttl time.Duration, namespace string)
- func (c *Cache) Snapshot() map[string]any
- func (c *Cache) StartCleanup(interval time.Duration)
- func (c *Cache) Stats() CacheStats
- type CacheCallbacks
- type CacheNamespace
- type CacheStats
- type SerializableItem
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache represents a thread-safe in-memory cache with advanced features
Example (Roundtrip) ¶
ExampleCache_roundtrip demonstrates a complete save/load cycle
// Create and populate original cache
originalCache := NewCache()
originalCache.Set("config:timeout", 30, 1*time.Hour)
originalCache.Set("config:retries", 3, 1*time.Hour)
// Add some namespaced data
userNS := originalCache.Namespace("users")
userNS.Set("1", map[string]interface{}{"name": "Alice", "active": true}, 2*time.Hour)
fmt.Printf("Original cache items: %d\n", originalCache.ItemCount())
// Save to buffer
var buf bytes.Buffer
err := originalCache.SaveTo(&buf)
if err != nil {
fmt.Printf("Save error: %v\n", err)
return
}
// Create new cache and load from buffer
newCache := NewCache()
err = newCache.LoadFrom(&buf)
if err != nil {
fmt.Printf("Load error: %v\n", err)
return
}
fmt.Printf("New cache items: %d\n", newCache.ItemCount())
// Verify data integrity
timeout, found := newCache.Get("config:timeout")
if found {
fmt.Printf("Timeout config: %v\n", timeout)
}
newUserNS := newCache.Namespace("users")
user, found := newUserNS.Get("1")
if found {
fmt.Printf("User data preserved: %v\n", user)
}
Output: Original cache items: 3 New cache items: 3 Timeout config: 30 User data preserved: map[active:true name:Alice]
func NewCacheWithOptions ¶
func NewCacheWithOptions(maxSize int, memoryLimit int64, callbacks *CacheCallbacks) *Cache
NewCacheWithOptions creates a cache with specified options
func (*Cache) ClearNamespace ¶
ClearNamespace removes all items from a namespace
func (*Cache) DeleteByPattern ¶
DeleteByPattern removes all keys matching a pattern
func (*Cache) DeleteMultiple ¶
DeleteMultiple removes multiple keys and returns the number deleted
func (*Cache) GetByPattern ¶
GetByPattern returns all key-value pairs matching a pattern
func (*Cache) GetByRegex ¶
GetByRegex returns all key-value pairs where keys match a regex pattern
func (*Cache) GetMultiple ¶
GetMultiple retrieves multiple keys at once
func (*Cache) HealthCheck ¶
HealthCheck returns cache health information
func (*Cache) ListNamespaces ¶
ListNamespaces returns all namespace names
func (*Cache) LoadFrom ¶ added in v1.0.3
LoadFrom reads cache contents from an io.Reader in JSON format
Example ¶
ExampleCache_LoadFrom demonstrates loading cache contents from any io.Reader
// JSON data representing cached items (could come from any io.Reader)
jsonData := `[
{
"key": "user:1",
"value": "John Doe",
"expiration": "2025-12-31T23:59:59Z",
"namespace": "",
"original_ttl": 300000000000
},
{
"key": "sessions:abc123",
"value": "active",
"expiration": "2025-12-31T23:59:59Z",
"namespace": "sessions",
"original_ttl": 1800000000000
}
]`
cache := NewCache()
reader := strings.NewReader(jsonData)
err := cache.LoadFrom(reader)
if err != nil {
fmt.Printf("Error loading cache: %v\n", err)
return
}
// Access the loaded data
user, found := cache.Get("user:1")
if found {
fmt.Printf("Loaded user: %s\n", user)
}
// Access namespaced data
sessionNS := cache.Namespace("sessions")
session, found := sessionNS.Get("abc123")
if found {
fmt.Printf("Loaded session: %s\n", session)
}
fmt.Printf("Total items loaded: %d\n", cache.ItemCount())
Output: Loaded user: John Doe Loaded session: active Total items loaded: 2
func (*Cache) LoadFromFile ¶
LoadFromFile loads cache contents from a JSON file
func (*Cache) MemoryUsage ¶
MemoryUsage returns current memory usage in bytes
func (*Cache) Namespace ¶
func (c *Cache) Namespace(name string) *CacheNamespace
Namespace returns a namespace-scoped cache interface
func (*Cache) SaveTo ¶ added in v1.0.3
SaveTo writes cache contents to an io.Writer in JSON format
Example ¶
ExampleCache_SaveTo demonstrates saving cache contents to any io.Writer
cache := NewCache()
// Add some data to the cache
cache.Set("user:1", "John Doe", 5*time.Minute)
cache.Set("user:2", "Jane Smith", 5*time.Minute)
// Create a namespace and add some data
sessionNS := cache.Namespace("sessions")
sessionNS.Set("abc123", "active", 30*time.Minute)
// Save to a bytes buffer (could be any io.Writer like a file, network connection, etc.)
var buf bytes.Buffer
err := cache.SaveTo(&buf)
if err != nil {
fmt.Printf("Error saving cache: %v\n", err)
return
}
// Print the JSON output (truncated for example)
output := buf.String()
if len(output) > 100 {
fmt.Printf("Saved cache data to buffer (approx %d bytes)\n", buf.Len()/100*100)
} else {
fmt.Printf("Cache data: %s", output)
}
Output: Saved cache data to buffer (approx 500 bytes)
func (*Cache) SaveToFile ¶
SaveToFile saves cache contents to a JSON file
func (*Cache) SetCallbacks ¶
func (c *Cache) SetCallbacks(callbacks *CacheCallbacks)
SetCallbacks sets event callback functions
func (*Cache) SetMaxSize ¶
SetMaxSize sets the maximum number of items in the cache
func (*Cache) SetMemoryLimit ¶
SetMemoryLimit sets the maximum memory usage in bytes
func (*Cache) SetMultiple ¶
SetMultiple sets multiple key-value pairs with the same TTL
func (*Cache) SetWithAbsoluteExpiry ¶
SetWithAbsoluteExpiry sets a key to expire at a specific time
func (*Cache) SetWithNamespace ¶
SetWithNamespace stores a value in a specific namespace
func (*Cache) StartCleanup ¶
StartCleanup starts automatic cleanup of expired items
type CacheCallbacks ¶
type CacheCallbacks struct {
OnExpire func(key string, value any)
OnEvict func(key string, value any)
OnSet func(key string, value any)
OnDelete func(key string, value any)
}
CacheCallbacks defines event handlers for cache operations
type CacheNamespace ¶
type CacheNamespace struct {
// contains filtered or unexported fields
}
CacheNamespace provides namespace-scoped operations
func (*CacheNamespace) Clear ¶
func (cn *CacheNamespace) Clear() int
Clear removes all items from the namespace
func (*CacheNamespace) Delete ¶
func (cn *CacheNamespace) Delete(key string) bool
Delete removes a key from the namespace
func (*CacheNamespace) Get ¶
func (cn *CacheNamespace) Get(key string) (any, bool)
Get retrieves a value from the namespace
func (*CacheNamespace) ItemCount ¶
func (cn *CacheNamespace) ItemCount() int
ItemCount returns the number of items in the namespace
func (*CacheNamespace) Keys ¶
func (cn *CacheNamespace) Keys() []string
Keys returns all keys in the namespace