diff --git a/docs/07.Reference/7.02.Filters.md b/docs/07.Reference/7.02.Filters.md index 095beda133..210b0cb646 100644 --- a/docs/07.Reference/7.02.Filters.md +++ b/docs/07.Reference/7.02.Filters.md @@ -2071,6 +2071,10 @@ package, and extra functions defined by Easegress: also an object, its type must also be `map[string]interface{}`. * **jsonEscape**: escape a string so that it can be used as the key or value in JSON text. +* **urlQueryEscape**: escapes the string so that it can be safely placed inside + a URL query, equivalent to the `urlquery` template function. +* **urlQueryUnescape**: performs the inverse transformation of `urlQueryEscape`, + decoding a URL-encoded string back to its origin form. Easegress injects existing requests/responses of the current context into the template engine at runtime, so we can use `.requests..` diff --git a/pkg/filters/builder/extrafuncs.go b/pkg/filters/builder/extrafuncs.go index ea90b7a168..4469ad33cf 100644 --- a/pkg/filters/builder/extrafuncs.go +++ b/pkg/filters/builder/extrafuncs.go @@ -21,6 +21,7 @@ import ( "encoding/json" "fmt" "net/http" + "net/url" "strconv" "strings" "text/template" @@ -154,4 +155,16 @@ var extraFuncs = template.FuncMap{ username, _, _ := req.(BasicAuth).BasicAuth() return username }, + + "urlQueryUnescape": func(s string) string { + unescapedStr, err := url.QueryUnescape(s) + if err != nil { + panic(err) + } + return unescapedStr + }, + + "urlQueryEscape": func(s string) string { + return url.QueryEscape(s) + }, } diff --git a/pkg/filters/builder/extrafuncs_test.go b/pkg/filters/builder/extrafuncs_test.go index 6aeda3609c..c564f5f2a6 100644 --- a/pkg/filters/builder/extrafuncs_test.go +++ b/pkg/filters/builder/extrafuncs_test.go @@ -59,6 +59,11 @@ func TestExtraFuncs(t *testing.T) { assert.Equal(`abcd\"ABCD`, extraFuncs["jsonEscape"].(func(s string) string)(`abcd"ABCD`)) + assert.Equal("https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FUTF-8%23Description", + extraFuncs["urlQueryEscape"].(func(s string) string)("https://en.wikipedia.org/wiki/UTF-8#Description")) + assert.Equal("https://en.wikipedia.org/wiki/UTF-8#Description", + extraFuncs["urlQueryUnescape"].(func(s string) string)("https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FUTF-8%23Description")) + assert.Panics(func() { extraFuncs["panic"].(func(v interface{}))("") }) }