2016-06-29 13:13:26 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type inMemCacheEntry struct {
|
|
|
|
Value string
|
|
|
|
Expires time.Time
|
|
|
|
}
|
|
|
|
|
2023-09-08 12:23:22 +00:00
|
|
|
// InMemCache implements the Cache interface for storage in memory
|
2016-06-29 13:13:26 +00:00
|
|
|
type InMemCache struct {
|
|
|
|
cache map[string]inMemCacheEntry
|
|
|
|
lock sync.RWMutex
|
|
|
|
}
|
|
|
|
|
2023-09-08 12:23:22 +00:00
|
|
|
// NewInMemCache creates a new InMemCache
|
2016-06-29 13:13:26 +00:00
|
|
|
func NewInMemCache() *InMemCache {
|
|
|
|
return &InMemCache{
|
|
|
|
cache: map[string]inMemCacheEntry{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-08 12:23:22 +00:00
|
|
|
// Get retrieves stored data
|
|
|
|
func (i *InMemCache) Get(namespace, key string) (value string, err error) {
|
2016-06-29 13:13:26 +00:00
|
|
|
i.lock.RLock()
|
|
|
|
defer i.lock.RUnlock()
|
|
|
|
|
|
|
|
e, ok := i.cache[namespace+"::"+key]
|
|
|
|
if !ok || e.Expires.Before(time.Now()) {
|
2023-09-08 12:23:22 +00:00
|
|
|
return "", ErrKeyNotFound
|
2016-06-29 13:13:26 +00:00
|
|
|
}
|
|
|
|
return e.Value, nil
|
|
|
|
}
|
|
|
|
|
2023-09-08 12:23:22 +00:00
|
|
|
// Set stores data
|
|
|
|
func (i *InMemCache) Set(namespace, key, value string, ttl time.Duration) (err error) {
|
2016-06-29 13:13:26 +00:00
|
|
|
i.lock.Lock()
|
|
|
|
defer i.lock.Unlock()
|
|
|
|
|
|
|
|
i.cache[namespace+"::"+key] = inMemCacheEntry{
|
|
|
|
Value: value,
|
|
|
|
Expires: time.Now().Add(ttl),
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-09-08 12:23:22 +00:00
|
|
|
// Delete deletes data
|
|
|
|
func (i *InMemCache) Delete(namespace, key string) (err error) {
|
2016-06-29 13:13:26 +00:00
|
|
|
i.lock.Lock()
|
|
|
|
defer i.lock.Unlock()
|
|
|
|
|
|
|
|
delete(i.cache, namespace+"::"+key)
|
|
|
|
return nil
|
|
|
|
}
|