-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage.go
69 lines (59 loc) · 1.18 KB
/
storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"os"
"sync"
"github.com/sirupsen/logrus"
)
var (
storageFile = flag.String("storage", "storage.json", "location of the storage file")
)
type storage struct {
store map[int64]string
storeLock sync.Mutex
saveLock sync.Mutex
}
func newStorage() (*storage, error) {
s := storage{}
if _, err := os.Stat(*storageFile); !os.IsNotExist(err) {
b, err := ioutil.ReadFile(*storageFile)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &s.store)
if err != nil {
return nil, err
}
} else {
s.store = make(map[int64]string)
}
return &s, nil
}
func (s *storage) Add(steamID int64, discordTag string) {
s.storeLock.Lock()
s.store[steamID] = discordTag
s.storeLock.Unlock()
go func() {
s.saveLock.Lock()
defer s.saveLock.Unlock()
s.storeLock.Lock()
b, err := json.Marshal(s.store)
s.storeLock.Unlock()
if err != nil {
logrus.Errorln(err)
return
}
err = ioutil.WriteFile(*storageFile, b, 0666)
if err != nil {
logrus.Errorln(err)
return
}
}()
}
func (s *storage) GetDiscordTag(steamID int64) string {
s.storeLock.Lock()
defer s.storeLock.Unlock()
return s.store[steamID]
}