conf: support render configure file using environment variables

This commit is contained in:
fatedier
2018-12-11 11:46:12 +08:00
parent b61cb14c8f
commit 25cfda5768
6 changed files with 167 additions and 48 deletions

View File

@ -885,9 +885,15 @@ func ParseRangeSection(name string, section ini.Section) (sections map[string]in
// if len(startProxy) is 0, start all
// otherwise just start proxies in startProxy map
func LoadAllConfFromIni(prefix string, conf ini.File, startProxy map[string]struct{}) (
func LoadAllConfFromIni(prefix string, content string, startProxy map[string]struct{}) (
proxyConfs map[string]ProxyConf, visitorConfs map[string]VisitorConf, err error) {
conf, errRet := ini.Load(strings.NewReader(content))
if errRet != nil {
err = errRet
return
}
if prefix != "" {
prefix += "."
}

64
models/config/value.go Normal file
View File

@ -0,0 +1,64 @@
package config
import (
"bytes"
"io/ioutil"
"os"
"strings"
"text/template"
)
var (
glbEnvs map[string]string
)
func init() {
glbEnvs = make(map[string]string)
envs := os.Environ()
for _, env := range envs {
kv := strings.Split(env, "=")
if len(kv) != 2 {
continue
}
glbEnvs[kv[0]] = kv[1]
}
}
type Values struct {
Envs map[string]string // environment vars
}
func GetValues() *Values {
return &Values{
Envs: glbEnvs,
}
}
func RenderContent(in string) (out string, err error) {
tmpl, errRet := template.New("frp").Parse(in)
if errRet != nil {
err = errRet
return
}
buffer := bytes.NewBufferString("")
v := GetValues()
err = tmpl.Execute(buffer, v)
if err != nil {
return
}
out = buffer.String()
return
}
func GetRenderedConfFromFile(path string) (out string, err error) {
var b []byte
b, err = ioutil.ReadFile(path)
if err != nil {
return
}
content := string(b)
out, err = RenderContent(content)
return
}