forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
url.go
70 lines (54 loc) · 1.32 KB
/
url.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
67
68
69
70
package common
import (
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
)
var hasScheme = regexp.MustCompile(`^([a-z][a-z0-9+\-.]*)://`)
// MakeURL creates the url based on the url configuration.
// Adds missing parts with defaults (scheme, host, port)
func MakeURL(defaultScheme string, defaultPath string, rawURL string, defaultPort int) (string, error) {
if defaultScheme == "" {
defaultScheme = "http"
}
if !hasScheme.MatchString(rawURL) {
rawURL = fmt.Sprintf("%v://%v", defaultScheme, rawURL)
}
addr, err := url.Parse(rawURL)
if err != nil {
return "", err
}
scheme := addr.Scheme
host := addr.Host
port := strconv.Itoa(defaultPort)
if host == "" {
host = "localhost"
} else {
// split host and optional port
if splitHost, splitPort, err := net.SplitHostPort(host); err == nil {
host = splitHost
port = splitPort
}
// Check if ipv6
if strings.Count(host, ":") > 1 && strings.Count(host, "]") == 0 {
host = "[" + host + "]"
}
}
// Assign default path if not set
if addr.Path == "" {
addr.Path = defaultPath
}
// reconstruct url
addr.Scheme = scheme
addr.Host = host + ":" + port
return addr.String(), nil
}
func EncodeURLParams(url string, params url.Values) string {
if len(params) == 0 {
return url
}
return strings.Join([]string{url, "?", params.Encode()}, "")
}