Skip to content

Commit 8a0fd2a

Browse files
committed
Use text/template instead of html/template for config pre-processing
Commit c95311d added support for multiple config formats in addition to pre-processing using Go's built-in templating system. The `html/template` package is equivalent to `text/template`, except that the former automatically escapes characters for inclusion in HTML. Configurations aren't plain text, but they're also certainly no HTML. The difference between the packages is noticeable when using `printf "%q"` for quoting of strings. An example from the included unittest: * `html/template`: `key = &#34;with space&#34;` * `text/template`: `key = "with space"` Signed-off-by: Michael Hanselmann <[email protected]>
1 parent 450b839 commit 8a0fd2a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Diff for: pkg/config/load.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ import (
1818
"bytes"
1919
"encoding/json"
2020
"fmt"
21-
"html/template"
2221
"os"
2322
"path/filepath"
2423
"strings"
24+
"text/template"
2525

2626
toml "github.com/pelletier/go-toml/v2"
2727
"github.com/samber/lo"

Diff for: pkg/config/load_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,29 @@ func TestLoadServerConfigStrictMode(t *testing.T) {
112112
}
113113
}
114114

115+
func TestRenderWithTemplate(t *testing.T) {
116+
tests := []struct {
117+
name string
118+
content string
119+
want string
120+
}{
121+
{"toml", tomlServerContent, tomlServerContent},
122+
{"yaml", yamlServerContent, yamlServerContent},
123+
{"json", jsonServerContent, jsonServerContent},
124+
{"template numeric", `key = {{ 123 }}`, "key = 123"},
125+
{"template string", `key = {{ "xyz" }}`, "key = xyz"},
126+
{"template quote", `key = {{ printf "%q" "with space" }}`, `key = "with space"`},
127+
}
128+
for _, test := range tests {
129+
t.Run(test.name, func(t *testing.T) {
130+
require := require.New(t)
131+
got, err := RenderWithTemplate([]byte(test.content), nil)
132+
require.NoError(err)
133+
require.EqualValues(test.want, string(got))
134+
})
135+
}
136+
}
137+
115138
func TestCustomStructStrictMode(t *testing.T) {
116139
require := require.New(t)
117140

0 commit comments

Comments
 (0)