weather/config.go

75 lines
1.4 KiB
Go
Raw Normal View History

2019-08-13 20:14:09 +00:00
package main
import (
"fmt"
"io/ioutil"
yaml "gopkg.in/yaml.v2"
)
type Config struct {
InfluxDB struct {
URL string `yaml:"url"`
Database string `yaml:"database"`
Measurement string `yaml:"measurement"`
Username string `yaml:"username"`
Password string `yaml:"password"`
} `yaml:"influxdb"`
OpenWeatherMap struct {
ApiKey string `yaml:"api_key"`
Units string `yaml:"units"`
} `yaml:"openweathermap"`
Cities []string `yaml:"cities"`
Interval int64 `yaml:"interval"`
}
func (c *Config) Load(path string) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = yaml.Unmarshal(data, &c)
if err != nil {
return err
}
c.Defaults()
err = c.Check()
if err != nil {
return err
}
return nil
}
func (c *Config) Defaults() {
if c.OpenWeatherMap.Units == "" {
c.OpenWeatherMap.Units = "metric"
}
if c.Interval == 0 {
c.Interval = 600
}
if c.InfluxDB.URL == "" {
c.InfluxDB.URL = "http://127.0.0.1:8086"
}
if c.InfluxDB.Measurement == "" {
c.InfluxDB.Measurement = "weather"
}
}
func (c *Config) Check() error {
if c.InfluxDB.Database == "" {
return fmt.Errorf("you must specify influxdb.database in config file")
}
if c.OpenWeatherMap.ApiKey == "" {
return fmt.Errorf("you must specify api_key in config file")
}
return nil
}