From e4e459a3f47d39d67d9ec61cbd3f8bc2efe8d14b Mon Sep 17 00:00:00 2001 From: Parham Alvani Date: Wed, 27 Dec 2023 05:52:21 +0000 Subject: [PATCH] Revert "fix: remove prefix for searching environment variables" This reverts commit 7272dd788b074cfff2df99cf71aa9b862e2c9873. --- pkg/koanf/config.go | 13 +++++++++---- pkg/koanf/config_test.go | 8 ++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/pkg/koanf/config.go b/pkg/koanf/config.go index f6ac3cc..87e1ffb 100644 --- a/pkg/koanf/config.go +++ b/pkg/koanf/config.go @@ -1,6 +1,7 @@ package koanf import ( + "fmt" "log" "strings" @@ -12,10 +13,14 @@ import ( ) // New reads configuration with koanf. -// def contains the default values. -func Provide[T interface{}](def T) T { +// service name is used for reading environment variables +// and def contains the default values. +func Provide[T interface{}](service string, def T) T { k := koanf.New(".") + // prefix indicates environment variables prefix. + prefix := fmt.Sprintf("%s_", strings.ToUpper(service)) + // create a new instance based-on given time. var instance T @@ -33,8 +38,8 @@ func Provide[T interface{}](def T) T { if err := k.Load( // replace __ with . in environment variables so you can reference field a in struct b // as a__b. - env.Provider("", ".", func(source string) string { - base := strings.ToLower(source) + env.Provider(prefix, ".", func(source string) string { + base := strings.ToLower(strings.TrimPrefix(source, prefix)) return strings.ReplaceAll(base, "__", ".") }), diff --git a/pkg/koanf/config_test.go b/pkg/koanf/config_test.go index 6d5030a..8b398e0 100644 --- a/pkg/koanf/config_test.go +++ b/pkg/koanf/config_test.go @@ -15,7 +15,7 @@ type Config struct { func TestProvideUsingDefault(t *testing.T) { require := require.New(t) - cfg := koanf.Provide(Config{ + cfg := koanf.Provide("testing", Config{ RabbitMQ: koanf.RabbitMQ{ Service: "rabbitmq.io", Username: "admin", @@ -28,12 +28,12 @@ func TestProvideUsingDefault(t *testing.T) { } func TestProvideUsingEnv(t *testing.T) { - os.Setenv("RABBITMQ__SERVICE", "rabbitmq.com") - defer os.Setenv("RABBITMQ__SERVICE", "") + os.Setenv("TESTING_RABBITMQ__SERVICE", "rabbitmq.com") + defer os.Setenv("TESTING_RABBITMQ__SERVICE", "") require := require.New(t) - cfg := koanf.Provide(Config{ + cfg := koanf.Provide("testing", Config{ RabbitMQ: koanf.RabbitMQ{ Service: "rabbitmq.io", Username: "admin",