mirror of
https://github.com/ThisTine/Snip.git
synced 2026-08-18 23:18:47 +07:00
49 lines
952 B
Go
49 lines
952 B
Go
package memory
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/snip/backend/internal/port"
|
|
)
|
|
|
|
type cacheEntry struct {
|
|
res port.Resolution
|
|
expires time.Time
|
|
}
|
|
|
|
// Cache is a TTL map standing in for Redis.
|
|
type Cache struct {
|
|
mu sync.RWMutex
|
|
m map[string]cacheEntry
|
|
}
|
|
|
|
func NewCache() *Cache {
|
|
return &Cache{m: make(map[string]cacheEntry)}
|
|
}
|
|
|
|
func (c *Cache) GetResolution(_ context.Context, code string) (port.Resolution, bool, error) {
|
|
c.mu.RLock()
|
|
e, ok := c.m[code]
|
|
c.mu.RUnlock()
|
|
if !ok || time.Now().After(e.expires) {
|
|
return port.Resolution{}, false, nil
|
|
}
|
|
return e.res, true, nil
|
|
}
|
|
|
|
func (c *Cache) SetResolution(_ context.Context, code string, r port.Resolution, ttl time.Duration) error {
|
|
c.mu.Lock()
|
|
c.m[code] = cacheEntry{res: r, expires: time.Now().Add(ttl)}
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
func (c *Cache) Invalidate(_ context.Context, code string) error {
|
|
c.mu.Lock()
|
|
delete(c.m, code)
|
|
c.mu.Unlock()
|
|
return nil
|
|
}
|