weather/config.go

94 lines
2 KiB
Go

/*
Copyright 2019 Adrien Waksberg
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"io/ioutil"
yaml "gopkg.in/yaml.v2"
)
// Config struct contains all options
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"`
}
// Load the config from a file
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
}
// Defaults set options with default value
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"
}
}
// Check if the options are good
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
}