From 944634613b6f9b04bc08d4804cf2f2d9babf09bc Mon Sep 17 00:00:00 2001 From: Martin Hebnes Pedersen Date: Sat, 4 Nov 2023 13:39:39 +0100 Subject: [PATCH] Support config overrides using env variables Override configuration values by setting PAT_* environment variables. This is handy when deploying a containerized/scripted setup. Syntax examples: * PAT_MYCALL=LA5NTA * PAT_ARDOP_ADDR="host:port" --- config.go | 17 ++++++++++++++--- go.mod | 1 + go.sum | 2 ++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/config.go b/config.go index 5c7a5284..f116c2f1 100644 --- a/config.go +++ b/config.go @@ -11,15 +11,26 @@ import ( "path" "strings" + "github.com/kelseyhightower/envconfig" "github.com/la5nta/pat/cfg" + "github.com/la5nta/pat/internal/buildinfo" "github.com/la5nta/pat/internal/debug" ) func LoadConfig(cfgPath string, fallback cfg.Config) (config cfg.Config, err error) { config, err = ReadConfig(cfgPath) - if os.IsNotExist(err) { - return fallback, WriteConfig(fallback, cfgPath) - } else if err != nil { + switch { + case os.IsNotExist(err): + config = fallback + if err := WriteConfig(config, cfgPath); err != nil { + return config, err + } + case err != nil: + return config, err + } + + // Environment variables overrides values from the config file + if err := envconfig.Process(buildinfo.AppName, &config); err != nil { return config, err } diff --git a/go.mod b/go.mod index 16e3a9c5..b5238483 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/gorilla/websocket v1.4.2 github.com/harenber/ptc-go/v2 v2.2.3 github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c + github.com/kelseyhightower/envconfig v1.4.0 github.com/la5nta/wl2k-go v0.11.8 github.com/microcosm-cc/bluemonday v1.0.16 github.com/n8jja/Pat-Vara v1.1.4 diff --git a/go.sum b/go.sum index 3108c430..849ab08d 100644 --- a/go.sum +++ b/go.sum @@ -34,6 +34,8 @@ github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6 h1:IIVxLyDUYErC950b8k github.com/howeyc/crc16 v0.0.0-20171223171357-2b2a61e366a6/go.mod h1:JslaLRrzGsOKJgFEPBP65Whn+rdwDQSk0I0MCRFe2Zw= github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c h1:aY2hhxLhjEAbfXOx2nRJxCXezC6CO2V/yN+OCr1srtk= github.com/howeyc/gopass v0.0.0-20190910152052-7cb4b85ec19c/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs= +github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8= +github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=