-
Notifications
You must be signed in to change notification settings - Fork 8
/
url_path.go
51 lines (46 loc) · 1.1 KB
/
url_path.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
package urlutil
import (
"errors"
"net/url"
"regexp"
"strings"
)
var leading *regexp.Regexp = regexp.MustCompile(`^/+`)
var trailing *regexp.Regexp = regexp.MustCompile(`/+$`)
// SplitPath splits a URL path string with optional removal of leading
// and trailing slashes.
func SplitPath(urlPath string, stripLeading, stripTrailing bool) []string {
urlPath = strings.TrimSpace(urlPath)
if stripLeading {
urlPath = leading.ReplaceAllString(urlPath, "")
}
if stripTrailing {
urlPath = trailing.ReplaceAllString(urlPath, "")
}
return strings.Split(urlPath, "/")
}
func GetPathLeaf(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
sep := "/"
p := strings.Trim(u.Path, sep)
parts := strings.Split(p, sep)
if len(parts) == 0 {
return "", errors.New("GetPathLeaf - no path")
}
return parts[len(parts)-1], nil
}
func ModifyPath(rawurl, newpath string) (string, error) {
u, err := url.Parse(rawurl)
if err != nil {
return "", err
}
newpath = strings.TrimSpace(newpath)
if newpath == "/" {
newpath = ""
}
u.Path = newpath
return CondenseURI(u.String()), nil
}