Skip to content

Commit

Permalink
implement 'urlQueryEscape' and 'urlQueryUnescape' template functions …
Browse files Browse the repository at this point in the history
…in filter builder (#1194)

This commit adds the 'urlQueryEscape' and 'urlQueryUnescape' functions to the template's extra functions ('extraFuncs'). These functions provide URL encoding and decoding capabilities.
  • Loading branch information
KevinQiangK committed Jan 12, 2024
1 parent 4096d50 commit b910a82
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/07.Reference/7.02.Filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<namespace>.<field>`
Expand Down
13 changes: 13 additions & 0 deletions pkg/filters/builder/extrafuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"text/template"
Expand Down Expand Up @@ -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)
},
}
5 changes: 5 additions & 0 deletions pkg/filters/builder/extrafuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}))("") })
}

Expand Down

0 comments on commit b910a82

Please sign in to comment.