From a8a6f8bfb2dd7f4e3e005f2df48a06261a1edb55 Mon Sep 17 00:00:00 2001 From: Anton Mashko Date: Thu, 14 Sep 2023 17:19:48 +0300 Subject: [PATCH] fix removing spaces from string --- json_test.go | 16 ++++++++++++++++ parser_primitives_test.go | 15 +++++++++++++++ type_primitive.go | 3 ++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/json_test.go b/json_test.go index d70071d..37bbf1f 100644 --- a/json_test.go +++ b/json_test.go @@ -277,3 +277,19 @@ func TestJsonConfig_ZeroValue_Ok(t *testing.T) { t.Errorf("incorrect result: %#v", tc) } } + +func TestJsonConfig_ValueWithSpace_Ok(t *testing.T) { + json := `{"foo": " bar "}` + tc := struct { + Foo string + }{} + jconf := envconf.NewJsonConfig() + jconf.Read([]byte(json)) + if err := envconf.ParseWithExternal(&tc, jconf); err != nil { + t.Errorf("failed to external parse. err=%s", err) + } + + if tc.Foo != " bar " { + t.Errorf("incorrect result: %#v", tc) + } +} diff --git a/parser_primitives_test.go b/parser_primitives_test.go index f2ecfab..367026a 100644 --- a/parser_primitives_test.go +++ b/parser_primitives_test.go @@ -358,3 +358,18 @@ func TestParse_UnsupportedFieldWithoutPanic_Ok(t *testing.T) { t.Fatal(err) } } + +func TestParse_ValueWithSpace_Ok(t *testing.T) { + cfg := struct { + Field1 string `env:"TEST_FIELD_1"` + }{} + + os.Setenv("TEST_FIELD_1", " test ") + if err := envconf.Parse(&cfg); err != nil { + t.Fatal(err) + } + + if cfg.Field1 != " test " { + t.Errorf("incorrect result:%#v", cfg) + } +} diff --git a/type_primitive.go b/type_primitive.go index 6cf0f73..d751e6f 100644 --- a/type_primitive.go +++ b/type_primitive.go @@ -110,6 +110,7 @@ func (t *primitiveType) define() error { } func setFromString(field reflect.Value, value string) error { + oval := value value = strings.Trim(value, " ") // native complex types switch field.Interface().(type) { @@ -142,7 +143,7 @@ func setFromString(field reflect.Value, value string) error { // primitives and collections switch field.Kind() { case reflect.String: - field.SetString(value) + field.SetString(oval) case reflect.Bool: i, err := strconv.ParseBool(value) if err != nil {