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