-
Notifications
You must be signed in to change notification settings - Fork 31
/
util.go
60 lines (48 loc) · 1.42 KB
/
util.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
// Copyright (c) 2018-2021, R.I. Pienaar and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0
package srvcache
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
)
// StringHostsToServers converts an array of servers like host:123 into an array of Servers collection
//
// if an empty scheme is given the string will be parsed by a url parser and the embedded
// scheme will be used, if that does not parse into a valid url then an error will be returned
func StringHostsToServers(hosts []string, scheme string) (servers Servers, err error) {
instances := make([]Server, len(hosts))
servers = NewServers()
for i, s := range hosts {
detectedScheme := scheme
s = strings.TrimSpace(s)
u, err := url.Parse(s)
if err == nil && u.Host != "" {
s = u.Host
if u.Scheme != "" {
detectedScheme = u.Scheme
}
}
host, sport, err := net.SplitHostPort(s)
if err != nil {
return servers, fmt.Errorf("could not parse host %s: %s", s, err)
}
port, err := strconv.ParseUint(sport, 10, 16)
if err != nil {
return servers, fmt.Errorf("could not parse host port %s: %s", s, err)
}
server := &BasicServer{
host: strings.TrimSpace(host),
port: uint16(port),
scheme: detectedScheme,
}
if scheme == "" && detectedScheme == "" {
return servers, fmt.Errorf("no scheme provided and %s has no scheme", s)
}
instances[i] = server
}
return NewServers(instances...), nil
}