feat(config): implement environment variable substitution in configuration file reading

This commit is contained in:
yusing
2025-09-09 23:33:05 +08:00
parent 4ebd1dbf32
commit bab9471bde
2 changed files with 53 additions and 1 deletions

View File

@@ -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")

View 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))
}