-
Notifications
You must be signed in to change notification settings - Fork 785
/
urls.go
66 lines (60 loc) · 1.55 KB
/
urls.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 util
import (
"bytes"
"net/url"
"strings"
)
// UrlJoin joins the given paths so that there is only ever one '/' character between the paths
func UrlJoin(paths ...string) string {
var buffer bytes.Buffer
last := len(paths) - 1
for i, path := range paths {
p := path
if i > 0 {
buffer.WriteString("/")
p = strings.TrimPrefix(p, "/")
}
if i < last {
p = strings.TrimSuffix(p, "/")
}
buffer.WriteString(p)
}
return buffer.String()
}
// UrlHostNameWithoutPort returns the host name without any port of the given URL like string
func UrlHostNameWithoutPort(rawUri string) (string, error) {
if strings.Index(rawUri, ":/") > 0 {
u, err := url.Parse(rawUri)
if err != nil {
return "", err
}
rawUri = u.Host
}
// must be a crazy kind of string so lets do our best
slice := strings.Split(rawUri, ":")
idx := 0
if len(slice) > 1 {
if len(slice) > 2 {
idx = 1
}
return strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(slice[idx], "/"), "/"), "/"), nil
}
return rawUri, nil
}
// URLEqual verifies if URLs are equal
func URLEqual(url1, url2 string) bool {
return url1 == url2 || strings.TrimSuffix(url1, "/") == strings.TrimSuffix(url2, "/")
}
// StripCredentialsFromURL strip credentials from URL
func StripCredentialsFromURL(u *url.URL) string {
pass, hasPassword := u.User.Password()
userName := u.User.Username()
if hasPassword {
textToReplace := pass + "@"
if userName != "" {
textToReplace = userName + ":" + textToReplace
}
return strings.Replace(u.String(), textToReplace, "", 1)
}
return u.String()
}