From 0659768beb2d395349dff017d3e39ec9859562cc Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Fri, 15 Mar 2019 00:36:00 -0400 Subject: [PATCH] Add environment flag to config --- config/config.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/config/config.go b/config/config.go index a2cda0c..a829886 100644 --- a/config/config.go +++ b/config/config.go @@ -16,12 +16,25 @@ const ( distConfigDir = "./dist" ) +// Environment represents the environment in which the app is being run, such as development or production +type Environment string + +const ( + // EnvironmentDev represents the development environment + EnvironmentDev Environment = "dev" + // EnvironmentProd represents the production environment + EnvironmentProd = "prod" +) + // ErrDefaultConfig is thrown when the default configuration is used var ErrDefaultConfig = errors.New("config: using default configuration") // ErrConfigNotLoaded is returned when the config has not been loaded yet var ErrConfigNotLoaded = errors.New("config: config not loaded") +// ErrBadEnvironment is returned when a bad environment is specified +var ErrBadEnvironment = errors.New("config: invalid value for environment") + // To prevent reading the config file each time we want a new config value, we store it as a package variable var config Config @@ -30,6 +43,7 @@ type Config struct { Server ServerConfig StoragePath string `yaml:"storage_path"` DatabaseURI string `yaml:"database_uri"` + Environment Environment } // ServerConfig stores configuration for the webserver @@ -38,6 +52,28 @@ type ServerConfig struct { Port int } +// UnmarshalYAML performs standard unmarshaling, followed by validation of the Environment enum +func (conf *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { + // Make a config type without the UnmarshalYAML function implemented, to avoid infinite recursion + type SafeConfig Config + safeConfig := (*SafeConfig)(conf) + err := unmarshal(safeConfig) + if err != nil { + return err + } + + switch conf.Environment { + case "": + conf.Environment = EnvironmentProd + fallthrough + case EnvironmentDev, EnvironmentProd: + return nil + default: + conf.Environment = "" + return ErrBadEnvironment + } +} + // Get loads the currently stored config. If one is not stored, panic. func Get() Config { if config == (Config{}) {