updown/config/config.go

79 lines
1.7 KiB
Go
Raw Normal View History

2019-02-25 04:10:52 +00:00
package config
import (
"errors"
"os"
"github.com/gobuffalo/packr/v2"
// explicit yaml designation is a work around for github.com/golang/go/issues/26882
yaml "gopkg.in/yaml.v2"
)
const (
configPath = "/etc/updown/config.yml"
distConfigBoxName = "distConfig"
distConfigName = "config.yml.dist"
)
// ErrDefaultConfig is thrown when the default configuration is used
var ErrDefaultConfig = errors.New("config: using default configuration")
// Config stores all configurations for the application
type Config struct {
Server ServerConfig
StoragePath string `yaml:"storage_path"`
}
// ServerConfig stores configuration for the webserver
type ServerConfig struct {
ListenAddr string `yaml:"listen_addr"`
Port int
}
// NewConfig checks for the stored configuration, and returns the default config and DefaultConfigError if not found.
func NewConfig() (Config, error) {
if shouldUseDistConfig() {
config, err := parseDistConfig()
if err != nil {
return Config{}, err
}
return config, ErrDefaultConfig
}
return parseSuppliedConfig()
}
func shouldUseDistConfig() bool {
_, err := os.Stat(configPath)
return os.IsNotExist(err)
}
func parseDistConfig() (Config, error) {
distBox := packr.New(distConfigBoxName, "./")
rawDistConfig, err := distBox.Find(distConfigName)
if err != nil {
return Config{}, err
}
distConfig := Config{}
err = yaml.UnmarshalStrict(rawDistConfig, &distConfig)
if err != nil {
return Config{}, err
}
return distConfig, nil
}
func parseSuppliedConfig() (Config, error) {
configFile, err := os.Open(configPath)
if err != nil {
return Config{}, err
}
configDecoder := yaml.NewDecoder(configFile)
configDecoder.SetStrict(true)
config := Config{}
return config, configDecoder.Decode(&config)
}