weather/config.go

95 lines
2 KiB
Go
Raw Permalink Normal View History

2019-08-22 17:37:45 +00:00
/*
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.
*/
2019-08-13 20:14:09 +00:00
package main
import (
2019-08-22 20:44:50 +00:00
"fmt"
"io/ioutil"
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
yaml "gopkg.in/yaml.v2"
2019-08-13 20:14:09 +00:00
)
2019-08-22 17:47:25 +00:00
// Config struct contains all options
2019-08-13 20:14:09 +00:00
type Config struct {
2019-08-22 20:44:50 +00:00
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"`
2019-08-13 20:14:09 +00:00
}
2019-08-22 17:47:25 +00:00
// Load the config from a file
2019-08-13 20:14:09 +00:00
func (c *Config) Load(path string) error {
2019-08-22 20:44:50 +00:00
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
2019-08-13 20:14:09 +00:00
}
2019-08-22 17:47:25 +00:00
// Defaults set options with default value
2019-08-13 20:14:09 +00:00
func (c *Config) Defaults() {
2019-08-22 20:44:50 +00:00
if c.OpenWeatherMap.Units == "" {
c.OpenWeatherMap.Units = "metric"
}
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
if c.Interval == 0 {
c.Interval = 600
}
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
if c.InfluxDB.URL == "" {
c.InfluxDB.URL = "http://127.0.0.1:8086"
}
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
if c.InfluxDB.Measurement == "" {
c.InfluxDB.Measurement = "weather"
}
2019-08-13 20:14:09 +00:00
}
2019-08-22 17:47:25 +00:00
// Check if the options are good
2019-08-13 20:14:09 +00:00
func (c *Config) Check() error {
2019-08-22 20:44:50 +00:00
if c.InfluxDB.Database == "" {
return fmt.Errorf("you must specify influxdb.database in config file")
}
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
if c.OpenWeatherMap.APIKey == "" {
return fmt.Errorf("you must specify api_key in config file")
}
2019-08-13 20:14:09 +00:00
2019-08-22 20:44:50 +00:00
return nil
2019-08-13 20:14:09 +00:00
}