From 956ca8607622508b49a35ec3c6c34b35a2898785 Mon Sep 17 00:00:00 2001 From: riftsin Date: Thu, 19 Jan 2023 12:27:57 +0100 Subject: [PATCH] fix: When trying to load a config with a field that has a non primitive type of inner type string from environment, Load panics, this fix adresses this issue --- configor_test.go | 21 +++++++++++++++++++++ utils.go | 6 +++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/configor_test.go b/configor_test.go index 5aed4d7..83de259 100644 --- a/configor_test.go +++ b/configor_test.go @@ -696,3 +696,24 @@ func TestLoad_FS(t *testing.T) { t.Error("expected to have foo: bar in config") } } + +func TestLoadConfigFromEnvWithFieldInnerTypeStringButRealTypeSomethingElse(t *testing.T) { + type myStringType string + type myTestConfig struct { + Name myStringType + } + var result myTestConfig + key := "MYTEST_NAME" + expected := "bob" + err := os.Setenv(key, expected) + if err != nil { + t.Fatal(err) + } + defer os.Unsetenv(key) + New(&Config{ + ENVPrefix: "MYTEST", + }).Load(&result) + if string(result.Name) != expected { + t.Errorf("expected '%s' got '%s'", expected, result.Name) + } +} diff --git a/utils.go b/utils.go index 18f88a9..91221ff 100644 --- a/utils.go +++ b/utils.go @@ -307,7 +307,11 @@ func (configor *Configor) processTags(config interface{}, prefixes ...string) er field.Set(reflect.ValueOf(true)) } case reflect.String: - field.Set(reflect.ValueOf(value)) + if field.Type() == reflect.TypeOf(value) { + field.Set(reflect.ValueOf(value)) + break + } + fallthrough default: if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil { return err