updown/config/config.go

99 lines
2.2 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"
distBoxName = "distConfig"
distConfigName = "config.yml"
distConfigDir = "./dist"
2019-02-25 04:10:52 +00:00
)
// ErrDefaultConfig is thrown when the default configuration is used
var ErrDefaultConfig = errors.New("config: using default configuration")
// To prevent reading the config file each time we want a new config value, we store it as a package variable
var config Config
2019-02-25 04:10:52 +00:00
// Config stores all configurations for the application
type Config struct {
Server ServerConfig
StoragePath string `yaml:"storage_path"`
2019-02-27 04:55:28 +00:00
DatabaseURI string `yaml:"database_uri"`
2019-02-25 04:10:52 +00:00
}
// ServerConfig stores configuration for the webserver
type ServerConfig struct {
ListenAddr string `yaml:"listen_addr"`
Port int
}
// GetConfig checks for the stored configuration, and returns the default config and DefaultConfigError if not found.
func GetConfig() (Config, error) {
if config != (Config{}) {
return config, nil
}
parsedConfig, err := loadConfig()
if err != nil && err != ErrDefaultConfig {
return Config{}, nil
}
config = parsedConfig
return config, err
}
func loadConfig() (Config, error) {
2019-02-25 04:10:52 +00:00
if shouldUseDistConfig() {
parsedConfig, err := parseDistConfig()
2019-02-25 04:10:52 +00:00
if err != nil {
return Config{}, err
}
return parsedConfig, ErrDefaultConfig
2019-02-25 04:10:52 +00:00
}
return parseSuppliedConfig()
}
func shouldUseDistConfig() bool {
_, err := os.Stat(configPath)
return os.IsNotExist(err)
}
func parseDistConfig() (Config, error) {
distBox := packr.New(distBoxName, distConfigDir)
2019-02-25 04:10:52 +00:00
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)
}