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{}, } }