truckstop/config/config.go

86 lines
1.3 KiB
Go

package config
import (
"encoding/json"
"io/ioutil"
"local/sandbox/contact/contact"
"local/storage"
"os"
"sync"
)
type Config struct {
Interval Duration
States []State
Storage []string
Client string
Once bool
Brokers struct {
NTG struct {
Mock bool
Cookie string
}
}
Emailer contact.Emailer
lock sync.Mutex
db storage.DB
}
var live Config
func configPath() string {
p, ok := os.LookupEnv("CONFIG")
if !ok {
p = "./config.json"
}
return p
}
func Refresh() error {
b, err := ioutil.ReadFile(configPath())
if err != nil {
return err
}
var c Config
if err := json.Unmarshal(b, &c); err != nil {
return err
}
if live.db != nil {
live.db.Close()
}
live = c
return nil
}
func Get() *Config {
return &live
}
func Set(other Config) {
b, err := json.MarshalIndent(other, "", " ")
if err != nil {
return
}
ioutil.WriteFile(configPath(), b, os.ModePerm)
Refresh()
}
func (c *Config) DB() storage.DB {
if c.db == nil {
c.lock.Lock()
defer c.lock.Unlock()
if c.db == nil {
if len(c.Storage) == 0 {
c.Storage = []string{storage.MAP.String()}
}
db, err := storage.New(storage.TypeFromString(c.Storage[0]), c.Storage[1:]...)
if err != nil {
panic(err)
}
c.db = db
}
}
return c.db
}