Add environment flag to config

master
Nick Krichevsky 2019-03-15 00:36:00 -04:00
parent e92aaf4284
commit 0659768beb
1 changed files with 36 additions and 0 deletions

View File

@ -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{}) {