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 (
|
2019-02-27 05:00:30 +00:00
|
|
|
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")
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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) {
|
2019-02-27 05:00:30 +00:00
|
|
|
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)
|
|
|
|
}
|