forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
107 lines (88 loc) · 2.14 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package elasticsearch
import (
"fmt"
"net"
"net/url"
"regexp"
"strings"
)
var hasScheme = regexp.MustCompile(`^([a-z][a-z0-9+\-.]*)://`)
// Creates the url based on the url configuration.
// Adds missing parts with defaults (scheme, host, port)
func getURL(defaultScheme string, defaultPath string, rawURL string) (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 := "9200"
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 makeURL(url, path, pipeline string, params map[string]string) string {
if len(params) == 0 && pipeline == "" {
return url + path
}
return strings.Join([]string{
url, path, "?", urlEncode(pipeline, params),
}, "")
}
// Encode parameters in url
func urlEncode(pipeline string, params map[string]string) string {
values := url.Values{}
for key, val := range params {
values.Add(key, string(val))
}
if pipeline != "" {
values.Add("pipeline", pipeline)
}
return values.Encode()
}
// Create path out of index, docType and id that is used for querying Elasticsearch
func makePath(index string, docType string, id string) (string, error) {
var path string
if len(docType) > 0 {
if len(id) > 0 {
path = fmt.Sprintf("/%s/%s/%s", index, docType, id)
} else {
path = fmt.Sprintf("/%s/%s", index, docType)
}
} else {
if len(id) > 0 {
if len(index) > 0 {
path = fmt.Sprintf("/%s/%s", index, id)
} else {
path = fmt.Sprintf("/%s", id)
}
} else {
path = fmt.Sprintf("/%s", index)
}
}
return path, nil
}