/* * @Author: Bartuccio Antoine * @Date: 2018-07-27 15:37:59 * @Last Modified by: klmp200 * @Last Modified time: 2018-07-27 16:06:51 */ package shared import ( "encoding/json" "io/ioutil" "sync" ) // General purpose chat info storage type chatData struct { mutex sync.Mutex data map[int64]map[string]interface{} } type chatDataFile struct { mutex sync.Mutex path string } var ChatData chatData var cdf chatDataFile // Init chat data meant to store infos about a chat. func InitChatData(path string) { cdf = chatDataFile{path: path} ChatData = chatData{data: make(map[int64]map[string]interface{})} ChatData.mutex.Lock() defer ChatData.mutex.Unlock() cdf.read() } func (c chatData) Set(chat int64, key string, data interface{}) { c.mutex.Lock() defer c.mutex.Unlock() if _, exists := c.data[chat]; !exists { c.data[chat] = make(map[string]interface{}) } c.data[chat][key] = data go cdf.write() } func (c chatData) Get(chat int64, key string) (interface{}, bool) { c.mutex.Lock() defer c.mutex.Unlock() m, exists := c.data[chat] if !exists { return nil, false } data, ok := m[key] if !ok { return nil, false } return data, true } func (c chatDataFile) read() { c.mutex.Lock() defer c.mutex.Unlock() data, err := ioutil.ReadFile(c.path) if err != nil { // File doesn't exist, skip import return } json.Unmarshal(data, &ChatData.data) } func (c chatDataFile) write() { c.mutex.Lock() defer c.mutex.Unlock() ChatData.mutex.Lock() defer ChatData.mutex.Unlock() data, _ := json.Marshal(ChatData.data) ioutil.WriteFile(c.path, data, 0770) }