bitrix_service/internal/obsids/cache.go

62 lines
1.1 KiB
Go

package obsids
import (
"encoding/json"
"net/http"
"sync/atomic"
"time"
)
func fetchIDs(sourceURL string) []int {
response, err := http.Get(sourceURL)
if err != nil {
return []int{}
}
defer response.Body.Close()
var ids []int
err = json.NewDecoder(response.Body).Decode(&ids)
if err != nil {
return []int{}
}
return ids
}
type Cache struct {
value atomic.Value // всегда хранит []int
interval time.Duration
sourceURL string
}
func NewCache(sourceURL string, interval time.Duration, defaultValue []int) *Cache {
c := &Cache{value: atomic.Value{}, interval: interval, sourceURL: sourceURL}
c.value.Store(defaultValue)
fetchedIDs := fetchIDs(c.sourceURL)
if len(fetchedIDs) > 0 {
c.value.Store(fetchedIDs)
}
return c
}
func (c *Cache) Get() []int {
return c.value.Load().([]int)
}
func (c *Cache) StartRefresh() {
go func() {
hourTicker := time.NewTicker(c.interval)
defer hourTicker.Stop()
for range hourTicker.C {
fetchedIDs := fetchIDs(c.sourceURL)
if len(fetchedIDs) > 0 {
c.value.Store(fetchedIDs)
}
}
}()
}