feat: cache
This commit is contained in:
parent
ef80892aa5
commit
5cdbbd2296
3 changed files with 148 additions and 0 deletions
53
cache/memory.go
vendored
Normal file
53
cache/memory.go
vendored
Normal 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),
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue