-
Notifications
You must be signed in to change notification settings - Fork 3
/
host.go
66 lines (56 loc) · 1.65 KB
/
host.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 netKit
import (
"fmt"
"github.com/richelieu-yang/chimera/v3/src/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/core/sliceKit"
"github.com/richelieu-yang/chimera/v3/src/validateKit"
"net"
"strconv"
)
var (
// SplitHost
/*
e.g.
fmt.Println(SplitHost("localhost:8080")) // "localhost" "8080" <nil>
fmt.Println(SplitHost("127.0.0.1")) // "" "" address 127.0.0.1: missing port in address
fmt.Println(SplitHost("localhost")) // "" "" address localhost: missing port in address
*/
SplitHost func(host string) (hostname, port string, err error) = net.SplitHostPort
)
// JoinToHost
/*
e.g.
fmt.Println(netKit.JoinToHost("127.0.0.1", 80)) // 127.0.0.1:80
fmt.Println(netKit.JoinToHost("", 8888)) // :8888
*/
func JoinToHost(hostname string, port int) string {
//return fmt.Sprintf("%s:%d", hostname, port)
return net.JoinHostPort(hostname, strconv.Itoa(port))
}
func IsHostname(str string) bool {
return validateKit.Hostname(str) == nil
}
func IsHost(str string) bool {
return validateKit.Host(str) == nil
}
// PolyfillHosts
/*
PS:
(1) host包含 ip 和 port. e.g."127.0.0.1:80"
@param minCount 至少要有几个元素?
@return 第1个返回值: 可能是一个新的slice实例
*/
func PolyfillHosts(hosts []string, minCount int) ([]string, error) {
if minCount <= 0 {
minCount = 1
}
hosts = sliceKit.PolyfillStringSlice(hosts)
//if err := sliceKit.AssertNotEmpty(hosts, "hosts"); err != nil {
// return nil, err
//}
tag := fmt.Sprintf("required,gte=%d,unique,dive,hostname_port", minCount)
if err := validateKit.Var(hosts, tag); err != nil {
return nil, errorKit.Wrapf(err, "hosts is invalid")
}
return hosts, nil
}