mirror of
https://github.com/yusing/godoxy.git
synced 2026-01-14 07:33:36 +01:00
feat(config): implement environment variable substitution in configuration file reading
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -215,10 +216,23 @@ func (cfg *Config) StartServers(opts ...*StartServersOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
var envRegex = regexp.MustCompile(`\$\{([^}]+)\}`) // e.g. ${CLOUDFLARE_API_KEY}
|
||||
var readFile = os.ReadFile
|
||||
|
||||
func (cfg *Config) readConfigFile() ([]byte, error) {
|
||||
data, err := readFile(common.ConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return envRegex.ReplaceAllFunc(data, func(match []byte) []byte {
|
||||
return strconv.AppendQuote(nil, os.Getenv(string(match[2:len(match)-1])))
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (cfg *Config) load() gperr.Error {
|
||||
const errMsg = "config load error"
|
||||
|
||||
data, err := os.ReadFile(common.ConfigPath)
|
||||
data, err := cfg.readConfigFile()
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Warn().Msg("config file not found, using default config")
|
||||
|
||||
38
internal/config/config_test.go
Normal file
38
internal/config/config_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfigEnvSubstitution(t *testing.T) {
|
||||
os.Setenv("CLOUDFLARE_AUTH_TOKEN", "test")
|
||||
readFile = func(_ string) ([]byte, error) {
|
||||
return []byte(`
|
||||
---
|
||||
autocert:
|
||||
email: "test@test.com"
|
||||
domains:
|
||||
- "*.test.com"
|
||||
provider: cloudflare
|
||||
options:
|
||||
auth_token: ${CLOUDFLARE_AUTH_TOKEN}
|
||||
`), nil
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
out, err := cfg.readConfigFile()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, `
|
||||
---
|
||||
autocert:
|
||||
email: "test@test.com"
|
||||
domains:
|
||||
- "*.test.com"
|
||||
provider: cloudflare
|
||||
options:
|
||||
auth_token: "test"
|
||||
`, string(out))
|
||||
}
|
||||
Reference in New Issue
Block a user