Skip to content

Commit

Permalink
cmd/golink: expose PathEscape and QueryEscape funcs
Browse files Browse the repository at this point in the history
Change-Id: I045d414fdbe265076a76ef6f652196761df3bb2c
  • Loading branch information
willnorris committed Jun 6, 2022
1 parent 4f58c2b commit 4735168
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
9 changes: 7 additions & 2 deletions golink.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,11 +243,16 @@ var reVarExpand = regexp.MustCompile(`\$\{\w+\}`)
type expandEnv struct {
Now time.Time

// Remaining path after short name. For example, in
// Path is the remaining path after short name. For example, in
// "http://go/who/amelie", Path is "amelie".
Path string
}

var expandFuncMap = template.FuncMap{
"PathEscape": url.PathEscape,
"QueryEscape": url.QueryEscape,
}

// expandLink returns the expanded long URL to redirect to, executing any
// embedded templates with env data.
//
Expand All @@ -262,7 +267,7 @@ func expandLink(long string, env expandEnv) (string, error) {
long += "{{with .Path}}/{{.}}{{end}}"
}
}
tmpl, err := template.New("").Parse(long)
tmpl, err := template.New("").Funcs(expandFuncMap).Parse(long)
if err != nil {
return "", err
}
Expand Down
12 changes: 12 additions & 0 deletions golink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,18 @@ func TestExpandLink(t *testing.T) {
remainder: "amelie",
want: "https://calendar.google.com/calendar/embed?mode=week&[email protected]",
},
{
name: "template-with-pathescape-func",
long: "http://host.com/{{QueryEscape .Path}}",
remainder: "a/b",
want: "http://host.com/a%2Fb",
},
{
name: "template-with-queryescape-func",
long: "http://host.com/{{QueryEscape .Path}}",
remainder: "a+b",
want: "http://host.com/a%2Bb",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 4735168

Please sign in to comment.