package main import ( _ "embed" "encoding/json" "io/ioutil" "time" "github.com/tidwall/pretty" ) //go:embed config.sample.json var cfgSample []byte type ServerConfig struct { Addr string `json:"addr"` Passwd string `json:"passwd"` } type TelegramConfig struct { AdminID int64 `json:"admin_id"` ChatID int64 `json:"chat_id"` URL string `json:"url"` Token string `json:"token"` } type GameConfig struct { TimeZone string `json:"timezone"` DailyAllotment time.Duration `json:"daily_allotment"` StartingAllotment time.Duration `json:"starting_allotment"` Threshold time.Duration `json:"threshold"` StartDate time.Time `json:"start_date"` } type ClientConfig struct { UserID int `json:"user_id"` Username string `json:"username"` Online bool `json:"online"` TimeLeft time.Duration `json:"time_left"` CompanyID uint8 `json:"company_id` } type Config struct { Server *ServerConfig `json:"server"` Telegram *TelegramConfig `json:"telegram"` Game *GameConfig `json:"game"` Clients map[int]*ClientConfig `json:"clients"` } // Init values for a config based on package defaults func (c *Config) Init() error { err := json.Unmarshal(cfgSample, &c) c.Clients = make(map[int]*ClientConfig) if err != nil { return err } return nil } // Load config values from a given file func (c *Config) Load(path string) error { err := c.Init() if err != nil { return err } b, err := ioutil.ReadFile(path) if err != nil { return c.Save(path) } err = json.Unmarshal(b, &c) if err != nil { return err } return c.Save(path) } // Save config values to a given file func (c *Config) Save(path string) error { b, err := c.Export() if err != nil { return nil } err = ioutil.WriteFile(path, b, 0644) return err } // Export config values as a bytestream func (c *Config) Export() ([]byte, error) { b, err := json.Marshal(c) if err != nil { return b, err } return pretty.Pretty(b), nil } func (c *Config) CompanyIsRegistered(id uint8) bool { for _, cc := range c.Clients { if cc.CompanyID == id { return true } } return false } func (c *Config) GetCompanyClient(id uint8) *ClientConfig { for _, cc := range c.Clients { if cc.CompanyID == id { return cc } } return nil }