Skip to content

Expose QueryEscape from net/url as a template func #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 11, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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