Skip to content

Commit

Permalink
Merge pull request #72 from md5/add-function-queryEscape
Browse files Browse the repository at this point in the history
Expose QueryEscape from net/url as a template func
  • Loading branch information
jwilder committed Mar 11, 2015
2 parents ec3c825 + acb2920 commit 6d52a2c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -311,6 +312,7 @@ func newTemplate(name string) *template.Template {
"last": arrayLast,
"replace": strings.Replace,
"parseJson": unmarshalJson,
"queryEscape": url.QueryEscape,
"sha1": hashSha1,
"split": strings.Split,
"trimPrefix": trimPrefix,
Expand Down
29 changes: 29 additions & 0 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,35 @@ func TestParseJson(t *testing.T) {
}
}

func TestQueryEscape(t *testing.T) {
tests := []struct {
tmpl string
context interface{}
expected string
}{
{`{{queryEscape .}}`, `example.com`, `example.com`},
{`{{queryEscape .}}`, `.example.com`, `.example.com`},
{`{{queryEscape .}}`, `*.example.com`, `%2A.example.com`},
{`{{queryEscape .}}`, `~^example\.com(\..*\.xip\.io)?$`, `~%5Eexample%5C.com%28%5C..%2A%5C.xip%5C.io%29%3F%24`},
}

for n, test := range tests {
tmplName := fmt.Sprintf("queryEscape-test-%d", n)
tmpl := template.Must(newTemplate(tmplName).Parse(test.tmpl))

var b bytes.Buffer
err := tmpl.ExecuteTemplate(&b, tmplName, test.context)
if err != nil {
t.Fatalf("Error executing template: %v", err)
}

got := b.String()
if test.expected != got {
t.Fatalf("Incorrect output found; expected %s, got %s", test.expected, got)
}
}
}

func TestArrayClosestExact(t *testing.T) {
if arrayClosest([]string{"foo.bar.com", "bar.com"}, "foo.bar.com") != "foo.bar.com" {
t.Fatal("Expected foo.bar.com")
Expand Down

0 comments on commit 6d52a2c

Please sign in to comment.