Fix: Concurrent access to map panic

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2021-04-01 12:28:51 +02:00
parent b7538d9b93
commit 8b575f7771
Signed by: luzifer
GPG Key ID: 0066F03ED215AD7D
2 changed files with 24 additions and 8 deletions

View File

@ -15,12 +15,12 @@ import (
var twitch = newTwitchClient()
type twitchClient struct {
apiCache twitchAPICache
apiCache *twitchAPICache
}
func newTwitchClient() *twitchClient {
return &twitchClient{
apiCache: make(twitchAPICache),
apiCache: newTwitchAPICache(),
}
}

View File

@ -4,19 +4,32 @@ import (
"crypto/sha256"
"fmt"
"strings"
"sync"
"time"
)
type (
twitchAPICache map[string]twitchAPICacheEntry
twitchAPICache struct {
data map[string]twitchAPICacheEntry
lock sync.RWMutex
}
twitchAPICacheEntry struct {
Data interface{}
ValidUntil time.Time
}
)
func (t twitchAPICache) Get(key []string) interface{} {
e := t[t.deriveKey(key)]
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)]
if e.ValidUntil.Before(time.Now()) {
return nil
}
@ -24,14 +37,17 @@ func (t twitchAPICache) Get(key []string) interface{} {
return e.Data
}
func (t twitchAPICache) Set(key []string, valid time.Duration, data interface{}) {
t[t.deriveKey(key)] = twitchAPICacheEntry{
func (t *twitchAPICache) Set(key []string, valid time.Duration, data interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
t.data[t.deriveKey(key)] = twitchAPICacheEntry{
Data: data,
ValidUntil: time.Now().Add(valid),
}
}
func (twitchAPICache) deriveKey(key []string) string {
func (*twitchAPICache) deriveKey(key []string) string {
sha := sha256.New()
fmt.Fprintf(sha, "%s", strings.Join(key, ":"))