Skip to content

Commit

Permalink
config environment variables replacement implemented.
Browse files Browse the repository at this point in the history
  • Loading branch information
ozge.onay authored and ozgeonay committed May 19, 2024
1 parent a795403 commit 0f7a453
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
19 changes: 19 additions & 0 deletions dcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"os"
"os/signal"
"reflect"
"regexp"
"strings"
"syscall"

"github.com/asaskevich/EventBus"
Expand Down Expand Up @@ -313,6 +315,23 @@ func newDcpConfig(path string) (config.Dcp, error) {
if err != nil {
return config.Dcp{}, err
}

envPattern := regexp.MustCompile(`\${([^}]+)}`)

matches := envPattern.FindAllStringSubmatch(string(file), -1)
for _, match := range matches {
envVar := match[1]
if value, exists := os.LookupEnv(envVar); exists {
updatedFile := strings.ReplaceAll(string(file), "${"+envVar+"}", value)
file = []byte(updatedFile)
}
}

err = yaml.Unmarshal(file, &c)
if err != nil {
return config.Dcp{}, err
}

return c, nil
}

Expand Down
40 changes: 40 additions & 0 deletions dcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,43 @@ func TestDcp(t *testing.T) {
test(t, version)
})
}

func TestNewDcpConfigWithEnvVariables(t *testing.T) {
os.Setenv("DCP_USERNAME", "envUser")
os.Setenv("DCP_PASSWORD", "envPass")
os.Setenv("DCP_BUCKET_NAME", "envBucket")

configContent := `
hosts: ["localhost:8091"]
username: ${DCP_USERNAME}
password: ${DCP_PASSWORD}
bucketName: ${DCP_BUCKET_NAME}
`
tmpFile, err := os.CreateTemp("", "config-*.yaml")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())

if _, err := tmpFile.Write([]byte(configContent)); err != nil {
t.Fatal(err)
}
if err := tmpFile.Close(); err != nil {
t.Fatal(err)
}

config, err := newDcpConfig(tmpFile.Name())
if err != nil {
t.Fatal(err)
}

if config.Username != "envUser" {
t.Errorf("expected username to be 'envUser', got '%s'", config.Username)
}
if config.Password != "envPass" {
t.Errorf("expected password to be 'envPass', got '%s'", config.Password)
}
if config.BucketName != "envBucket" {
t.Errorf("expected bucketName to be 'envBucket', got '%s'", config.BucketName)
}
}

0 comments on commit 0f7a453

Please sign in to comment.