-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
66 lines (56 loc) · 1.6 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package kittycad
import (
"bytes"
"fmt"
"net/url"
"strings"
"text/template"
)
// resolveRelative combines a url base with a relative path.
func resolveRelative(basestr, relstr string) string {
u, _ := url.Parse(basestr)
rel, _ := url.Parse(relstr)
u = u.ResolveReference(rel)
us := u.String()
us = strings.Replace(us, "%7B", "{", -1)
us = strings.Replace(us, "%7D", "}", -1)
return us
}
// expandURL subsitutes any {encoded} strings in the URL passed in using
// the map supplied.
func expandURL(u *url.URL, expansions map[string]string) error {
origPath := u.Path
t, err := template.New("url").Parse(u.Path)
if err != nil {
return fmt.Errorf("parsing template for url path %q failed: %v", u.Path, err)
}
var b bytes.Buffer
if err := t.Execute(&b, expansions); err != nil {
return fmt.Errorf("executing template for url path failed: %v", err)
}
// set the parameters
u.Path = b.String()
// escape the expansions
for k, v := range expansions {
expansions[k] = url.QueryEscape(v)
}
var bt bytes.Buffer
if err := t.Execute(&bt, expansions); err != nil {
return fmt.Errorf("executing template for url path failed: %v", err)
}
// set the parameters
u.RawPath = bt.String()
// For any extra arguments that were not in the template, parse the args
// as path paramters.
values := u.Query()
for k, v := range expansions {
if !strings.Contains(origPath, fmt.Sprintf("{{.%s}}", k)) {
values.Set(k, v)
}
}
// Set the path parameters
u.RawQuery = values.Encode()
// We want colons in the query string to be unescaped.
u.RawQuery = strings.Replace(u.RawQuery, "%253A", ":", -1)
return nil
}