Changed implementation of issue #304 fix

It no longer uses regular expressions.
It supports both the Unix `{$ENV_VAR}` _and_ the Windows `{%ENV_VAR%}`
syntax.
Added test for both Unix and Windows env. syntax.
This commit is contained in:
Michael Banzon 2015-11-15 11:16:37 +01:00
parent e166ebf68b
commit d448c919e8
2 changed files with 32 additions and 8 deletions

View file

@ -4,14 +4,9 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
) )
var (
envRegEx = regexp.MustCompile("{\\$[^}]+}")
)
type parser struct { type parser struct {
Dispenser Dispenser
block serverBlock // current server block being parsed block serverBlock // current server block being parsed
@ -337,10 +332,23 @@ func (sb serverBlock) HostList() []string {
} }
func getValFromEnv(s string) string { func getValFromEnv(s string) string {
envRefs := envRegEx.FindAllString(s, -1) s = replaceEnvReferences(s, "{$", "}")
s = replaceEnvReferences(s, "{%", "%}")
return s
}
for _, ref := range envRefs { func replaceEnvReferences(s, refStart, refEnd string) string {
s = strings.Replace(s, ref, os.Getenv(ref[2:len(ref)-1]), -1) index := strings.Index(s, refStart)
for index != -1 {
endIndex := strings.Index(s, refEnd)
if endIndex != -1 {
ref := s[index : endIndex+len(refEnd)]
s = strings.Replace(s, ref, os.Getenv(ref[len(refStart):len(ref)-len(refEnd)]), -1)
} else {
return s
}
index = strings.Index(s, refStart)
} }
return s return s

View file

@ -391,6 +391,22 @@ func TestEnvironmentReplacement(t *testing.T) {
[]address{{"127.0.0.1", "1234"}}, []address{{"127.0.0.1", "1234"}},
[]address{{"localhost", "8080"}}, []address{{"localhost", "8080"}},
}}, }},
{`{%MY_ADDRESS%}`, [][]address{
{{"servername.com", ""}},
}},
{`{%MY_ADDRESS%}:{%MY_PORT%}`, [][]address{
[]address{{"servername.com", "8080"}},
}},
{`{%MY_ADDRESS2%}:1234 {
}
localhost:{%MY_PORT%} {
}`, [][]address{
[]address{{"127.0.0.1", "1234"}},
[]address{{"localhost", "8080"}},
}},
} { } {
p := testParser(test.input) p := testParser(test.input)
blocks, err := p.parseAll() blocks, err := p.parseAll()