/* * @Author: Bartuccio Antoine * @Date: 2018-07-24 14:41:03 * @Last Modified by: klmp200 * @Last Modified time: 2018-07-24 17:49:51 */ package shared import ( "encoding/json" "io/ioutil" "sync" ) type users struct { mutex sync.Mutex data map[string]map[string]string } type usersFile struct { mutex sync.Mutex path string } var Users users var uf usersFile func InitUsers(users_file_path string) { uf = usersFile{} uf.path = users_file_path Users = users{} Users.mutex.Lock() defer Users.mutex.Unlock() Users.data = make(map[string]map[string]string) uf.read() } // Get an info about a given user func (u users) Get(username string, key string) (string, bool) { u.mutex.Lock() defer u.mutex.Unlock() user, exists := u.data[username] if !exists { return "", false } if _, exists = user[key]; !exists { return "", false } return user[key], true } // Add an info about a given user func (u users) Set(username string, key, data string) { u.mutex.Lock() defer u.mutex.Unlock() if _, exists := u.data[username]; !exists { u.data[username] = make(map[string]string) } u.data[username][key] = data go uf.write() } func (u usersFile) read() { u.mutex.Lock() defer u.mutex.Unlock() data, err := ioutil.ReadFile(u.path) if err != nil { // File doesn't exist, skip import return } json.Unmarshal(data, &Users.data) } func (u usersFile) write() { u.mutex.Lock() defer u.mutex.Unlock() Users.mutex.Lock() defer Users.mutex.Unlock() data, _ := json.Marshal(Users.data) ioutil.WriteFile(u.path, data, 0770) }