Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support bool for env tag #2593

Merged
merged 1 commit into from Nov 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions core/mapping/unmarshaler.go
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -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)
Expand Down
41 changes: 41 additions & 0 deletions core/mapping/unmarshaler_test.go
Expand Up @@ -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"`
Expand Down