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>
This commit is contained in:
parent
ef80892aa5
commit
98eb17d9f3
10 changed files with 984 additions and 0 deletions
68
cache/memory.go
vendored
Normal file
68
cache/memory.go
vendored
Normal file
|
@ -0,0 +1,68 @@
|
|||
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{},
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue