46 lines
744 B
Go
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,
|
|
}
|
|
}
|