Skip to content

Commit

Permalink
Revert "fix: remove prefix for searching environment variables"
Browse files Browse the repository at this point in the history
This reverts commit 7272dd7.
  • Loading branch information
Parham Alvani committed Dec 27, 2023
1 parent cdabba3 commit e4e459a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
13 changes: 9 additions & 4 deletions pkg/koanf/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package koanf

import (
"fmt"
"log"
"strings"

Expand All @@ -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

Expand All @@ -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, "__", ".")
}),
Expand Down
8 changes: 4 additions & 4 deletions pkg/koanf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down

0 comments on commit e4e459a

Please sign in to comment.