Skip to content

Commit 6d52a2c

Browse files
committed
Merge pull request #72 from md5/add-function-queryEscape
Expose QueryEscape from net/url as a template func
2 parents ec3c825 + acb2920 commit 6d52a2c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

template.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"io"
1010
"io/ioutil"
1111
"log"
12+
"net/url"
1213
"os"
1314
"path/filepath"
1415
"reflect"
@@ -311,6 +312,7 @@ func newTemplate(name string) *template.Template {
311312
"last": arrayLast,
312313
"replace": strings.Replace,
313314
"parseJson": unmarshalJson,
315+
"queryEscape": url.QueryEscape,
314316
"sha1": hashSha1,
315317
"split": strings.Split,
316318
"trimPrefix": trimPrefix,

template_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,35 @@ func TestParseJson(t *testing.T) {
550550
}
551551
}
552552

553+
func TestQueryEscape(t *testing.T) {
554+
tests := []struct {
555+
tmpl string
556+
context interface{}
557+
expected string
558+
}{
559+
{`{{queryEscape .}}`, `example.com`, `example.com`},
560+
{`{{queryEscape .}}`, `.example.com`, `.example.com`},
561+
{`{{queryEscape .}}`, `*.example.com`, `%2A.example.com`},
562+
{`{{queryEscape .}}`, `~^example\.com(\..*\.xip\.io)?$`, `~%5Eexample%5C.com%28%5C..%2A%5C.xip%5C.io%29%3F%24`},
563+
}
564+
565+
for n, test := range tests {
566+
tmplName := fmt.Sprintf("queryEscape-test-%d", n)
567+
tmpl := template.Must(newTemplate(tmplName).Parse(test.tmpl))
568+
569+
var b bytes.Buffer
570+
err := tmpl.ExecuteTemplate(&b, tmplName, test.context)
571+
if err != nil {
572+
t.Fatalf("Error executing template: %v", err)
573+
}
574+
575+
got := b.String()
576+
if test.expected != got {
577+
t.Fatalf("Incorrect output found; expected %s, got %s", test.expected, got)
578+
}
579+
}
580+
}
581+
553582
func TestArrayClosestExact(t *testing.T) {
554583
if arrayClosest([]string{"foo.bar.com", "bar.com"}, "foo.bar.com") != "foo.bar.com" {
555584
t.Fatal("Expected foo.bar.com")

0 commit comments

Comments
 (0)