2019-12-10 14:15:27 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
2019-12-28 14:38:38 +00:00
|
|
|
"sync"
|
2019-12-10 14:15:27 +00:00
|
|
|
|
|
|
|
"git.trj.tw/golang/utils"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Storage -
|
|
|
|
type Storage struct {
|
|
|
|
m map[string]interface{}
|
|
|
|
filePath string
|
2019-12-28 14:38:38 +00:00
|
|
|
sync.Mutex
|
2019-12-10 14:15:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var s *Storage
|
|
|
|
|
|
|
|
// New storage
|
|
|
|
func New() *Storage {
|
|
|
|
if s == nil {
|
|
|
|
s = &Storage{
|
|
|
|
m: make(map[string]interface{}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get storage
|
|
|
|
func Get() *Storage { return s }
|
|
|
|
|
|
|
|
// Load storage data from file
|
2019-12-28 14:38:38 +00:00
|
|
|
func (p *Storage) Load(filePath string, ignoreNotExist bool) (err error) {
|
2019-12-10 14:15:27 +00:00
|
|
|
filePath = utils.ParsePath(filePath)
|
2019-12-28 14:38:38 +00:00
|
|
|
exist := utils.CheckExists(filePath, false)
|
|
|
|
if !exist && !ignoreNotExist {
|
2019-12-10 14:15:27 +00:00
|
|
|
return errors.New("storage file not found")
|
|
|
|
}
|
|
|
|
p.filePath = filePath
|
|
|
|
|
2019-12-28 14:38:38 +00:00
|
|
|
if exist {
|
|
|
|
b, err := ioutil.ReadFile(filePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-12-10 14:15:27 +00:00
|
|
|
|
2019-12-28 14:38:38 +00:00
|
|
|
if err := json.Unmarshal(b, &p.m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2019-12-10 14:15:27 +00:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Storage) Write() (err error) {
|
2019-12-28 14:38:38 +00:00
|
|
|
p.Lock()
|
|
|
|
defer p.Unlock()
|
2019-12-10 14:15:27 +00:00
|
|
|
b, err := json.Marshal(p.m)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = ioutil.WriteFile(p.filePath, b, 0664)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get data by key
|
|
|
|
func (p *Storage) Get(key string) (data interface{}, ok bool) {
|
|
|
|
data, ok = p.m[key]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set data by key
|
2019-12-28 14:38:38 +00:00
|
|
|
func (p *Storage) Set(key string, value interface{}) {
|
|
|
|
p.m[key] = value
|
|
|
|
_ = p.Write()
|
|
|
|
}
|
2019-12-10 14:15:27 +00:00
|
|
|
|
|
|
|
// Delete data by key
|
2019-12-28 14:38:38 +00:00
|
|
|
func (p *Storage) Delete(key string) {
|
|
|
|
delete(p.m, key)
|
|
|
|
_ = p.Write()
|
|
|
|
}
|