feat: cache

This commit is contained in:
Felipe M 2025-03-23 20:59:57 +01:00
parent ef80892aa5
commit 5cdbbd2296
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8
3 changed files with 148 additions and 0 deletions

53
cache/memory.go vendored Normal file
View file

@ -0,0 +1,53 @@
package cache
import (
"sync"
"time"
"git.nakama.town/fmartingr/gotoolkit/model"
)
var _ model.Cache = (*MemoryCache)(nil)
type MemoryCache struct {
data map[string]any
dataMu sync.RWMutex
}
func (c *MemoryCache) Get(key string) (result any, err error) {
c.dataMu.RLock()
defer c.dataMu.RUnlock()
result, exists := c.data[key]
if !exists {
return result, model.ErrCacheKeyDontExist
}
return
}
func (c *MemoryCache) GetWithExpiry(key string, expiration time.Duration) (any, error) {
// TODO: Implement expiration in memory cache.
return c.Get(key)
}
func (c *MemoryCache) Set(key string, value any) error {
c.dataMu.Lock()
c.data[key] = value
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]any),
}
}