-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuri_tools.go
More file actions
69 lines (59 loc) · 1.92 KB
/
uri_tools.go
File metadata and controls
69 lines (59 loc) · 1.92 KB
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
67
68
69
package maas
import (
"fmt"
"regexp"
"strings"
)
var IgnoreTrailUrlSlashRegexPreCompile map[string]*regexp.Regexp
var replaceReg *regexp.Regexp
var DefaultIgnoreTrailSlashUrl = []string{
"license-key/{osystem}/{distro_series}",
"scripts/{name}",
"nodes/{system_id}/blockdevices/{device_id}/partition/{id}",
}
func init() {
var err error
// will replace `{.*}` => .*? for url regex string
replaceReg, _ = regexp.Compile("{.*?}")
err = ReloadRegex(DefaultIgnoreTrailSlashUrl)
if err != nil {
panic(fmt.Errorf("load ignore trail url regex failed with err: %v", err))
}
}
func ReloadRegex(regexUrl []string) error {
tmpRegexPreCompile := make(map[string]*regexp.Regexp)
for _, u := range regexUrl {
t := replaceReg.ReplaceAllString(u, ".*?")
tReg, err := regexp.Compile(t + "$")
// anyone compiled fail, will return error
if err != nil {
return fmt.Errorf("compile regix: `%s` failed with err: %+v", t, err)
}
tmpRegexPreCompile[u] = tReg
}
// all regexp string compile success
IgnoreTrailUrlSlashRegexPreCompile = tmpRegexPreCompile
return nil
}
// JoinURLs joins a base URL and a subpath together.
// Regardless of whether baseURL ends in a trailing slash (or even multiple
// trailing slashes), or whether there are any leading slashes at the begining
// of path, the two will always be joined together by a single slash.
func JoinURLs(baseURL, path string) string {
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(path, "/")
}
// EnsureTrailingSlash appends a slash at the end of the given string unless
// there already is one.
// This is used to create the kind of normalized URLs that Django expects.
// (to avoid Django's redirection when an URL does not ends with a slash.)
func EnsureTrailingSlash(u string) string {
for _, rgx := range IgnoreTrailUrlSlashRegexPreCompile {
if rgx.FindStringIndex(u) != nil {
return u
}
}
if strings.HasSuffix(u, "/") {
return u
}
return u + "/"
}