From 8982e1dd3fd3eedb507b058a2184c725d9e20c9c Mon Sep 17 00:00:00 2001 From: William Petit Date: Fri, 17 Jul 2020 11:45:35 +0200 Subject: [PATCH] feature(config): allow environment variable override --- cmd/server/main.go.gotpl | 4 ++++ internal/config/config.go | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/cmd/server/main.go.gotpl b/cmd/server/main.go.gotpl index b647809..743b718 100644 --- a/cmd/server/main.go.gotpl +++ b/cmd/server/main.go.gotpl @@ -76,6 +76,10 @@ func main() { } + if err := config.WithEnvironment(conf); err != nil { + log.Fatalf("%+v", errors.Wrap(err, "could not override config with environment")) + } + // Dump configuration if asked if dumpConfig { if err := config.Dump(conf, os.Stdout); err != nil { diff --git a/internal/config/config.go b/internal/config/config.go index 42688cc..239448b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -7,11 +7,12 @@ import ( "github.com/pkg/errors" + "github.com/caarlos0/env/v6" "gopkg.in/yaml.v2" ) type Config struct { - Debug bool `yaml:"debug"` + Debug bool `yaml:"debug" env:"DEBUG"` HTTP HTTPConfig `yaml:"http"` } @@ -32,12 +33,12 @@ func NewFromFile(filepath string) (*Config, error) { } type HTTPConfig struct { - Address string `yaml:"address"` - CookieAuthenticationKey string `yaml:"cookieAuthenticationKey"` - CookieEncryptionKey string `yaml:"cookieEncryptionKey"` - CookieMaxAge int `yaml:"cookieMaxAge"` - TemplateDir string `yaml:"templateDir"` - PublicDir string `yaml:"publicDir"` + Address string `yaml:"address" env:"HTTP_ADDRESS"` + CookieAuthenticationKey string `yaml:"cookieAuthenticationKey" env:"HTTP_COOKIE_AUTHENTICATION_KEY"` + CookieEncryptionKey string `yaml:"cookieEncryptionKey" env:"HTTP_COOKIE_ENCRYPTION_KEY"` + CookieMaxAge int `yaml:"cookieMaxAge" env:"HTTP_COOKIE_MAX_AGE"` + TemplateDir string `yaml:"templateDir" env:"HTTP_TEMPLATE_DIR"` + PublicDir string `yaml:"publicDir" env:"HTTP_PUBLIC_DIR"` } func NewDumpDefault() *Config { @@ -71,3 +72,11 @@ func Dump(config *Config, w io.Writer) error { return nil } + +func WithEnvironment(conf *Config) error { + if err := env.Parse(conf); err != nil { + return err + } + + return nil +}