86 lines
1.3 KiB
Go
86 lines
1.3 KiB
Go
package storage
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"sync"
|
|
|
|
"git.trj.tw/golang/utils"
|
|
)
|
|
|
|
// Storage -
|
|
type Storage struct {
|
|
m map[string]interface{}
|
|
filePath string
|
|
sync.Mutex
|
|
}
|
|
|
|
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
|
|
func (p *Storage) Load(filePath string, ignoreNotExist bool) (err error) {
|
|
filePath = utils.ParsePath(filePath)
|
|
exist := utils.CheckExists(filePath, false)
|
|
if !exist && !ignoreNotExist {
|
|
return errors.New("storage file not found")
|
|
}
|
|
p.filePath = filePath
|
|
|
|
if exist {
|
|
b, err := ioutil.ReadFile(filePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := json.Unmarshal(b, &p.m); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func (p *Storage) Write() (err error) {
|
|
p.Lock()
|
|
defer p.Unlock()
|
|
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
|
|
func (p *Storage) Set(key string, value interface{}) {
|
|
p.m[key] = value
|
|
_ = p.Write()
|
|
}
|
|
|
|
// Delete data by key
|
|
func (p *Storage) Delete(key string) {
|
|
delete(p.m, key)
|
|
_ = p.Write()
|
|
}
|