2021-03-27 17:55:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2021-04-01 10:28:51 +00:00
|
|
|
"sync"
|
2021-03-27 17:55:38 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2021-04-01 10:28:51 +00:00
|
|
|
twitchAPICache struct {
|
|
|
|
data map[string]twitchAPICacheEntry
|
|
|
|
lock sync.RWMutex
|
|
|
|
}
|
2021-03-27 17:55:38 +00:00
|
|
|
twitchAPICacheEntry struct {
|
|
|
|
Data interface{}
|
|
|
|
ValidUntil time.Time
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-04-01 10:28:51 +00:00
|
|
|
func newTwitchAPICache() *twitchAPICache {
|
|
|
|
return &twitchAPICache{
|
|
|
|
data: make(map[string]twitchAPICacheEntry),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *twitchAPICache) Get(key []string) interface{} {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-04-01 10:28:51 +00:00
|
|
|
func (t *twitchAPICache) Set(key []string, valid time.Duration, data interface{}) {
|
|
|
|
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-04-01 10:28:51 +00:00
|
|
|
func (*twitchAPICache) deriveKey(key []string) string {
|
2021-03-27 17:55:38 +00:00
|
|
|
sha := sha256.New()
|
|
|
|
|
|
|
|
fmt.Fprintf(sha, "%s", strings.Join(key, ":"))
|
|
|
|
|
|
|
|
return fmt.Sprintf("sha256:%x", sha.Sum(nil))
|
|
|
|
}
|