Skip to content
Snippets Groups Projects
Verified Commit 06ee56ee authored by Volker Schukai's avatar Volker Schukai :alien:
Browse files

fix the prefix of the env function now works

parent 44601b62
No related branches found
No related tags found
No related merge requests found
......@@ -7,6 +7,7 @@ import (
"os"
"reflect"
"strconv"
"strings"
)
func (s *Settings[C]) InitFromEnv(prefix string) *Settings[C] {
......@@ -21,12 +22,18 @@ func (s *Settings[C]) InitFromEnv(prefix string) *Settings[C] {
}
}()
if prefix != "" {
prefix = strings.ToUpper(prefix) + "_"
}
err := runOnTags(&s.config, []string{envTagKey}, func(k string, field reflect.Value) {
if !field.CanSet() {
return
}
k = prefix + strings.ToUpper(k)
v, found := os.LookupEnv(k)
if !found {
return // env not found
......
......@@ -20,6 +20,7 @@ func TestReadmeExample2(t *testing.T) {
// Set value
os.Setenv("HOST", "www.example.com")
defer os.Unsetenv("HOST")
s := New(config)
//fmt.Println(s.Config().Host) // localhost
......@@ -31,6 +32,27 @@ func TestReadmeExample2(t *testing.T) {
}
func TestWithPrefix(t *testing.T) {
config := struct {
Host string `env:"HOST"`
}{
Host: "localhost",
}
// Set value
os.Setenv("XYZ_HOST", "www.example.com")
defer os.Unsetenv("XYZ_HOST")
s := New(config)
//fmt.Println(s.Config().Host) // localhost
assert.Equal(t, s.Config().Host, "localhost")
s.InitFromEnv("XYZ") // no prefix
//fmt.Println(s.Config().Host) // www.example.com
assert.Equal(t, s.Config().Host, "www.example.com")
}
func TestFromEnvNotSet(t *testing.T) {
config := ConfigStruct6{
IA: 1234,
......@@ -43,6 +65,7 @@ func TestFromEnvNotSet(t *testing.T) {
// Value not set
s.InitFromEnv("VALUE_IB")
defer os.Unsetenv("VALUE_IB")
if s.Config().IA != 1234 {
t.Errorf("Expected 1234, got %d", s.Config().IA)
......@@ -61,7 +84,7 @@ func TestFromEnv(t *testing.T) {
s := New(config)
// Value not set
s.InitFromEnv("VALUE_IB")
s.InitFromEnv("NIX")
if s.Config().IA != 1234 {
t.Errorf("Expected 1234, got %d", s.Config().IA)
......@@ -69,7 +92,8 @@ func TestFromEnv(t *testing.T) {
// Set value
os.Setenv("VALUE_IB", "i-am-b")
s.InitFromEnv("VALUE_IB")
defer os.Unsetenv("VALUE_IB")
s.InitFromEnv("")
if s.Config().IB != "i-am-b" {
t.Errorf("Expected i-am-b, got %s", s.Config().IB)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment