country-geo-locations/internal/cache/cache.go

39 lines
566 B
Go

package cache
import (
"sync"
"time"
)
type Cache struct {
ttl time.Duration
store sync.Map
}
func NewCache(ttl time.Duration) *Cache {
return &Cache{
ttl: ttl,
}
}
func (c *Cache) Count() uint {
var counter uint
c.store.Range(func(_, _ any) bool {
counter++
return true
})
return counter
}
func (c *Cache) Set(key, value uint) {
c.store.Store(key, value)
time.AfterFunc(c.ttl, func() {
c.store.Delete(key)
})
}
func (c *Cache) Get(key uint) (uint, bool) {
output, _ := c.store.Load(key)
value, ok := output.(uint)
return value, ok
}