Skip to content

Commit

Permalink
feat: config environment variables replacement implemented. (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
ozgeonay authored May 19, 2024
1 parent a795403 commit 6c5264c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
18 changes: 18 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,22 @@ 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("", "dcpConfig-*.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)
}

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

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

0 comments on commit 6c5264c

Please sign in to comment.