caddyfile: Fix import replacing unrelated placeholders (#4129)

* caddyfile: Fix `import` replacing unrelated placeholders

See https://caddy.community/t/snippet-issue-works-outside-snippet/12231

So it turns out that `NewReplacer()` gives a replacer with some global defaults (like `{env.*}` and some system and time placeholders), which is not ideal when running `import` because we just want to replace `{args.*}` only, and nothing else.

* caddyfile: Add test
This commit is contained in:
Francis Lavoie 2021-04-22 20:29:04 -04:00 committed by GitHub
parent 1e218e1d2e
commit a8d45277ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 1 deletions

View File

@ -321,7 +321,7 @@ func (p *parser) doImport() error {
args := p.RemainingArgs() args := p.RemainingArgs()
// add args to the replacer // add args to the replacer
repl := caddy.NewReplacer() repl := caddy.NewEmptyReplacer()
for index, arg := range args { for index, arg := range args {
repl.Set("args."+strconv.Itoa(index), arg) repl.Set("args."+strconv.Itoa(index), arg)
} }

View File

@ -0,0 +1,31 @@
(foo) {
respond {env.FOO}
}
:80 {
import foo
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":80"
],
"routes": [
{
"handle": [
{
"body": "{env.FOO}",
"handler": "static_response"
}
]
}
]
}
}
}
}
}

View File

@ -36,6 +36,18 @@ func NewReplacer() *Replacer {
return rep return rep
} }
// NewEmptyReplacer returns a new Replacer,
// without the global default replacements.
func NewEmptyReplacer() *Replacer {
rep := &Replacer{
static: make(map[string]interface{}),
}
rep.providers = []ReplacerFunc{
rep.fromStatic,
}
return rep
}
// Replacer can replace values in strings. // Replacer can replace values in strings.
// A default/empty Replacer is not valid; // A default/empty Replacer is not valid;
// use NewReplacer to make one. // use NewReplacer to make one.