mirror of
https://github.com/Luzifer/twitch-bot.git
synced 2024-11-08 08:10:08 +00:00
Fix: Concurrent access to map panic
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
b7538d9b93
commit
8b575f7771
2 changed files with 24 additions and 8 deletions
|
@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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, ":"))
|
||||
|
|
Loading…
Reference in a new issue