Files
outfit-voting-abi26/internal/cache.go
T
tueem 85e4df52a5
build / Go-Build (push) Successful in 1m1s
feat(*): initial commit
2026-06-24 00:16:21 +02:00

46 lines
744 B
Go

package internal
import (
"sync"
"time"
)
type CacheItem[T any] struct {
item T
imutex sync.Mutex
expiry time.Time
TTLSeconds uint
FetchFunc func() (T, error)
}
func (c *CacheItem[T]) Get() (T, error) {
c.imutex.Lock()
defer c.imutex.Unlock()
if !c.expiry.After(time.Now()) {
c.expiry = time.Now().Add(time.Duration(c.TTLSeconds) * time.Second)
item, err := c.FetchFunc()
if err != nil {
return item, err
}
c.item = item
}
return c.item, nil
}
func (c *CacheItem[T]) Invalidate() {
c.imutex.Lock()
defer c.imutex.Unlock()
c.expiry = time.Now()
}
func NewCache[T any](fetchfunc func() (T, error), ttl uint) CacheItem[T] {
return CacheItem[T]{
TTLSeconds: ttl,
FetchFunc: fetchfunc,
}
}