From 8a0fd2acd5c745f61f6eda6466652c665cdd6623 Mon Sep 17 00:00:00 2001 From: Michael Hanselmann Date: Tue, 4 Feb 2025 22:20:31 +0100 Subject: [PATCH] Use text/template instead of html/template for config pre-processing Commit c95311d1 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 = "with space"` * `text/template`: `key = "with space"` Signed-off-by: Michael Hanselmann --- pkg/config/load.go | 2 +- pkg/config/load_test.go | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pkg/config/load.go b/pkg/config/load.go index fa814fd0..fa394dda 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -18,10 +18,10 @@ import ( "bytes" "encoding/json" "fmt" - "html/template" "os" "path/filepath" "strings" + "text/template" toml "github.com/pelletier/go-toml/v2" "github.com/samber/lo" diff --git a/pkg/config/load_test.go b/pkg/config/load_test.go index b3f77800..980a332a 100644 --- a/pkg/config/load_test.go +++ b/pkg/config/load_test.go @@ -112,6 +112,29 @@ func TestLoadServerConfigStrictMode(t *testing.T) { } } +func TestRenderWithTemplate(t *testing.T) { + tests := []struct { + name string + content string + want string + }{ + {"toml", tomlServerContent, tomlServerContent}, + {"yaml", yamlServerContent, yamlServerContent}, + {"json", jsonServerContent, jsonServerContent}, + {"template numeric", `key = {{ 123 }}`, "key = 123"}, + {"template string", `key = {{ "xyz" }}`, "key = xyz"}, + {"template quote", `key = {{ printf "%q" "with space" }}`, `key = "with space"`}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + got, err := RenderWithTemplate([]byte(test.content), nil) + require.NoError(err) + require.EqualValues(test.want, string(got)) + }) + } +} + func TestCustomStructStrictMode(t *testing.T) { require := require.New(t)