gotoolkit/cache/memory.go
Felipe M. 98eb17d9f3 feat: cache + paths (#1)
- Added helper function `ExpandUser`
- Added basic cache impmentations for in-memory and file based caches.

Reviewed-on: #1
Co-authored-by: Felipe M. <me@fmartingr.com>
Co-committed-by: Felipe M. <me@fmartingr.com>
2025-03-23 23:46:28 +01:00

68 lines
1.2 KiB
Go

package cache
import (
"sync"
"time"
"git.nakama.town/fmartingr/gotoolkit/model"
)
var _ model.Cache = (*MemoryCache)(nil)
type MemoryCache struct {
data map[string]model.CacheItem
dataMu sync.RWMutex
}
func (c *MemoryCache) Get(key string) (result any, err error) {
c.dataMu.RLock()
item, exists := c.data[key]
if !exists {
c.dataMu.RUnlock()
return result, model.ErrCacheKeyDontExist
}
// Check expiration while still holding the lock
if item.TTL != nil && item.TTL.Before(time.Now()) {
c.dataMu.RUnlock()
_ = c.Delete(key)
return result, model.ErrCacheKeyDontExist
}
value := item.Value
c.dataMu.RUnlock()
return value, nil
}
func (c *MemoryCache) Set(key string, value any, opts ...model.CacheOption) error {
item := model.CacheItem{
Key: key,
Value: value,
}
for _, opt := range opts {
opt(&item)
}
c.dataMu.Lock()
c.data[key] = item
c.dataMu.Unlock()
return nil
}
func (c *MemoryCache) Delete(key string) error {
c.dataMu.Lock()
delete(c.data, key)
c.dataMu.Unlock()
return nil
}
func NewMemoryCache() *MemoryCache {
return &MemoryCache{
data: make(map[string]model.CacheItem),
dataMu: sync.RWMutex{},
}
}