-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
91 lines (74 loc) · 1.7 KB
/
user.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"encoding/json"
"io/ioutil"
"log"
"path"
"sync"
)
var (
// users is map only because go has no good set implementation
users = make(map[int64]bool, 0)
userMutex = sync.Mutex{}
userFile = path.Join("data", "users.json")
)
// Load the users from the disk.
// This function should be called once
func loadUsers() error {
// Lock the mutex to ensure only one is modifying the data
userMutex.Lock()
defer userMutex.Unlock()
// Read the file
byteValue, err := ioutil.ReadFile(userFile)
if err != nil {
log.Println("The user file does not exist")
return nil
}
// Parse the file
err = json.Unmarshal(byteValue, &users)
if err != nil {
return err
}
return nil
}
// Save the current userlist to the disk
// Note: the caller must lock the userMutex to avoid race conditions
func saveUsers() error {
// Create the content
byteValue, err := json.Marshal(users)
if err != nil {
return err
}
// Write the file
return ioutil.WriteFile(userFile, byteValue, 0777)
}
func getUsers() []int64 {
userMutex.Lock()
defer userMutex.Unlock()
result := make([]int64, 0, len(users))
for k, _ := range users {
result = append(result, k)
}
return result
}
// Returns true if the specified userID is in the list of subscribed users
func isUser(user int64) bool {
userMutex.Lock()
defer userMutex.Unlock()
_, ok := users[user]
return ok
}
// Add the specified user to the list of subscribed users
func addUser(user int64) error {
userMutex.Lock()
defer userMutex.Unlock()
users[user] = true
return saveUsers()
}
// Remove the specified user from the list
func removeUser(user int64) error {
userMutex.Lock()
defer userMutex.Unlock()
delete(users, user)
return saveUsers()
}