53 lines
920 B
Go
53 lines
920 B
Go
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),
|
|
}
|
|
}
|