Skip to content

Commit

Permalink
fix: environment variable parsing
Browse files Browse the repository at this point in the history
This is more of a workaround than the correct solution. It only fixes top-level ENV variables parsing.
  • Loading branch information
hacdias authored Jul 25, 2024
1 parent f6a0707 commit 814462b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import (
)

const (
DefaultScope = "/"
DefaultModify = false
DefaultDebug = false
DefaultNoSniff = false
DefaultTLS = false
DefaultAuth = false
DefaultCert = "cert.pem"
Expand Down Expand Up @@ -65,8 +69,15 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
v.SetEnvPrefix("wd")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
// TODO: use new env struct bind feature when it's released in viper.
// This should make it redundant to set defaults for things that are
// empty or false.

// Defaults shared with flags
v.SetDefault("Scope", DefaultScope)
v.SetDefault("Modify", DefaultModify)
v.SetDefault("Debug", DefaultDebug)
v.SetDefault("NoSniff", DefaultNoSniff)
v.SetDefault("TLS", DefaultTLS)
v.SetDefault("Cert", DefaultCert)
v.SetDefault("Key", DefaultKey)
Expand Down
22 changes: 22 additions & 0 deletions lib/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -195,3 +196,24 @@ rules:
require.NotEmpty(t, cfg.Rules[1].Path)
require.Nil(t, cfg.Rules[1].Regexp)
}

func TestConfigEnv(t *testing.T) {
require.NoError(t, os.Setenv("WD_PORT", "1234"))
require.NoError(t, os.Setenv("WD_DEBUG", "true"))
require.NoError(t, os.Setenv("WD_MODIFY", "true"))
require.NoError(t, os.Setenv("WD_SCOPE", "/test"))

cfg, err := ParseConfig("", nil)
require.NoError(t, err)

assert.Equal(t, 1234, cfg.Port)
assert.Equal(t, "/test", cfg.Scope)
assert.Equal(t, true, cfg.Debug)
assert.Equal(t, true, cfg.Modify)

// Reset
require.NoError(t, os.Setenv("WD_PORT", ""))
require.NoError(t, os.Setenv("WD_DEBUG", ""))
require.NoError(t, os.Setenv("WD_MODIFY", ""))
require.NoError(t, os.Setenv("WD_SCOPE", ""))
}

0 comments on commit 814462b

Please sign in to comment.