2021-08-19 13:33:56 +00:00
|
|
|
package twitch
|
2021-03-27 17:55:38 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2021-04-01 10:28:51 +00:00
|
|
|
"sync"
|
2021-03-27 17:55:38 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2024-01-01 16:52:18 +00:00
|
|
|
// APICache is used to cache API responses in order not to ask the
|
|
|
|
// API over and over again for information seldom changing
|
2021-08-19 13:33:56 +00:00
|
|
|
APICache struct {
|
2021-04-01 10:28:51 +00:00
|
|
|
data map[string]twitchAPICacheEntry
|
|
|
|
lock sync.RWMutex
|
|
|
|
}
|
2021-08-19 13:33:56 +00:00
|
|
|
|
2021-03-27 17:55:38 +00:00
|
|
|
twitchAPICacheEntry struct {
|
|
|
|
Data interface{}
|
|
|
|
ValidUntil time.Time
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-08-19 13:33:56 +00:00
|
|
|
func newTwitchAPICache() *APICache {
|
|
|
|
return &APICache{
|
2021-04-01 10:28:51 +00:00
|
|
|
data: make(map[string]twitchAPICacheEntry),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// Get returns the stored data or nil for the given cache-key
|
2021-08-19 13:33:56 +00:00
|
|
|
func (t *APICache) Get(key []string) interface{} {
|
2021-04-01 10:28:51 +00:00
|
|
|
t.lock.RLock()
|
|
|
|
defer t.lock.RUnlock()
|
|
|
|
|
|
|
|
e := t.data[t.deriveKey(key)]
|
2021-03-27 17:55:38 +00:00
|
|
|
if e.ValidUntil.Before(time.Now()) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return e.Data
|
|
|
|
}
|
|
|
|
|
2024-01-01 16:52:18 +00:00
|
|
|
// Set sets the stored data for the given cache-key
|
2021-08-19 13:33:56 +00:00
|
|
|
func (t *APICache) Set(key []string, valid time.Duration, data interface{}) {
|
2021-04-01 10:28:51 +00:00
|
|
|
t.lock.Lock()
|
|
|
|
defer t.lock.Unlock()
|
|
|
|
|
|
|
|
t.data[t.deriveKey(key)] = twitchAPICacheEntry{
|
2021-03-27 17:55:38 +00:00
|
|
|
Data: data,
|
|
|
|
ValidUntil: time.Now().Add(valid),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-19 13:33:56 +00:00
|
|
|
func (*APICache) deriveKey(key []string) string {
|
2024-01-01 16:52:18 +00:00
|
|
|
return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(strings.Join(key, ":"))))
|
2021-03-27 17:55:38 +00:00
|
|
|
}
|