-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
77 lines (66 loc) · 1.31 KB
/
db.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
70
71
72
73
74
75
76
77
package main
import (
"encoding/json"
"log"
"os"
"time"
"golang.org/x/oauth2"
)
type UserData struct {
Token *oauth2.Token
}
func (db *Database) dumpToFile() {
// Dangerous!
fi, err := os.OpenFile(db.dbFile, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer fi.Close()
dbData, _ := json.Marshal(db.userTable)
if _, err := fi.Write(dbData); err != nil {
log.Fatal(err)
}
}
type Database struct {
dbFile string
messages chan uint8
userTable map[string]*UserData
}
func newDatabase(dbFile string) *Database {
var db *Database
dat, err := os.ReadFile(dbFile)
if err != nil {
log.Printf("DB file `%s` does not exist.", dbFile)
db = &Database{
dbFile: dbFile,
messages: make(chan uint8),
userTable: make(map[string]*UserData),
}
return db
}
err = json.Unmarshal(dat, &db)
if err != nil {
removeErr := os.Remove(dbFile)
if removeErr != nil {
log.Fatal(err)
}
log.Fatal(err)
}
return &Database{
dbFile: dbFile,
messages: make(chan uint8),
userTable: make(map[string]*UserData),
}
}
func (db *Database) run() {
ticker := time.NewTicker(5 * time.Second)
for {
select {
case message := <-db.messages:
log.Printf("DB Hub got message: %s", message)
case t := <-ticker.C:
log.Println("Dumped DB at: ", t)
go db.dumpToFile()
}
}
}