pi-calendar/pkg/storage/storage.go

71 lines
1.1 KiB
Go

package storage
import (
"encoding/json"
"errors"
"io/ioutil"
"git.trj.tw/golang/utils"
)
// Storage -
type Storage struct {
m map[string]interface{}
filePath string
}
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) (err error) {
filePath = utils.ParsePath(filePath)
if !utils.CheckExists(filePath, false) {
return errors.New("storage file not found")
}
p.filePath = filePath
b, err := ioutil.ReadFile(filePath)
if err != nil {
return
}
err = json.Unmarshal(b, &p.m)
return
}
func (p *Storage) Write() (err error) {
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 }
// Delete data by key
func (p *Storage) Delete(key string) { delete(p.m, key) }