From 936e6f8b89f984f8bb9b9d8a033a37b2af121283 Mon Sep 17 00:00:00 2001 From: kevin Date: Sat, 12 Nov 2022 00:18:18 +0800 Subject: [PATCH] feat: support bool for env tag --- core/mapping/unmarshaler.go | 9 +++++++ core/mapping/unmarshaler_test.go | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 9fcf1de5e852..c75bc50c9a76 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "reflect" + "strconv" "strings" "sync" "time" @@ -342,6 +343,14 @@ func (u *Unmarshaler) processFieldWithEnvValue(field reflect.StructField, value envVal string, opts *fieldOptionsWithContext, fullName string) error { fieldKind := field.Type.Kind() switch fieldKind { + case reflect.Bool: + val, err := strconv.ParseBool(envVal) + if err != nil { + return fmt.Errorf("unmarshal field %q with environment variable, %w", fullName, err) + } + + value.SetBool(val) + return nil case durationType.Kind(): if err := fillDurationValue(fieldKind, value, envVal); err != nil { return fmt.Errorf("unmarshal field %q with environment variable, %w", fullName, err) diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index 6fdcdaacbb60..f806bfbb426d 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -3186,6 +3186,47 @@ func TestUnmarshal_EnvFloatOverwrite(t *testing.T) { assert.Equal(t, float32(123.45), v.Age) } +func TestUnmarshal_EnvBoolTrue(t *testing.T) { + type Value struct { + Enable bool `key:"enable,env=TEST_NAME_BOOL_TRUE"` + } + + const envName = "TEST_NAME_BOOL_TRUE" + os.Setenv(envName, "true") + defer os.Unsetenv(envName) + + var v Value + assert.NoError(t, UnmarshalKey(emptyMap, &v)) + assert.True(t, v.Enable) +} + +func TestUnmarshal_EnvBoolFalse(t *testing.T) { + type Value struct { + Enable bool `key:"enable,env=TEST_NAME_BOOL_FALSE"` + } + + const envName = "TEST_NAME_BOOL_FALSE" + os.Setenv(envName, "false") + defer os.Unsetenv(envName) + + var v Value + assert.NoError(t, UnmarshalKey(emptyMap, &v)) + assert.False(t, v.Enable) +} + +func TestUnmarshal_EnvBoolBad(t *testing.T) { + type Value struct { + Enable bool `key:"enable,env=TEST_NAME_BOOL_BAD"` + } + + const envName = "TEST_NAME_BOOL_BAD" + os.Setenv(envName, "bad") + defer os.Unsetenv(envName) + + var v Value + assert.Error(t, UnmarshalKey(emptyMap, &v)) +} + func TestUnmarshal_EnvDuration(t *testing.T) { type Value struct { Duration time.Duration `key:"duration,env=TEST_NAME_DURATION"`