Skip to content

Commit

Permalink
add regexp.Match to template funcs
Browse files Browse the repository at this point in the history
Add a "Match" template func, which uses regexp.MatchString to match a
value against a regular expression pattern.

Fixes #125

Signed-off-by: Will Norris <[email protected]>
  • Loading branch information
willnorris committed May 7, 2024
1 parent 41e9dc9 commit ed6c396
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
6 changes: 6 additions & 0 deletions golink.go
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,12 @@ var expandFuncMap = texttemplate.FuncMap{
"PathEscape": url.PathEscape,
"QueryEscape": url.QueryEscape,
"TrimSuffix": strings.TrimSuffix,
"Match": regexMatch,
}

func regexMatch(pattern string, s string) bool {
b, _ := regexp.MatchString(pattern, s)
return b
}

// expandLink returns the expanded long URL to redirect to, executing any
Expand Down
12 changes: 12 additions & 0 deletions golink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,18 @@ func TestExpandLink(t *testing.T) {
remainder: "a/",
want: "http://host.com/a",
},
{
name: "template-with-match-func",
long: `http://host.com/{{if Match "\\d+" .Path}}id/{{.Path}}{{else}}search/{{.Path}}{{end}}`,
remainder: "123",
want: "http://host.com/id/123",
},
{
name: "template-with-match-func2",
long: `http://host.com/{{if Match "\\d+" .Path}}id/{{.Path}}{{else}}search/{{.Path}}{{end}}`,
remainder: "query",
want: "http://host.com/search/query",
},
{
name: "relative-link",
long: `rel`,
Expand Down
2 changes: 2 additions & 0 deletions tmpl/help.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ <h2 id="advanced">Advanced destination links</h2>
<ul>
<li><code>PathEscape</code> is the <a href="https://pkg.go.dev/net/url#PathEscape">url.PathEscape</a> function for escaping values inside a URL path.
<li><code>QueryEscape</code> is the <a href="https://pkg.go.dev/net/url#QueryEscape">url.QueryEscape</a> function for escaping values inside a URL query.
<li><code>TrimSuffix</code> is the <a href="https://pkg.go.dev/strings#TrimSuffix">strings.TrimSuffix</a> function for removing a trailing suffix.
<li><code>Match</code> is the <a href="https://pkg.go.dev/regexp#MatchString">regexp.MatchString</a> function for matching a regular expression pattern.
</ul>

<p>
Expand Down

0 comments on commit ed6c396

Please sign in to comment.