-
Notifications
You must be signed in to change notification settings - Fork 3
/
address.go
executable file
·118 lines (106 loc) · 2.46 KB
/
address.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
108
109
110
111
112
113
114
115
116
117
118
// Package netKit
/*
PS: Golang对于host的定义 不同于 js.
e.g. "127.0.0.1:8888"
host in Golang: "127.0.0.1"
host in js: "127.0.0.1:8888"
*/
package netKit
import (
"fmt"
"github.com/richelieu-yang/chimera/v2/src/core/errorKit"
"github.com/richelieu-yang/chimera/v2/src/core/strKit"
"net"
"strconv"
)
type (
Address struct {
// Hostname 也可以是ip
Hostname string
Port int
}
)
func (addr *Address) String() string {
return fmt.Sprintf("%s:%d", addr.Hostname, addr.Port)
}
func JoinHostnameAndPort(hostname string, port int) string {
//addr := &Address{
// Hostname: hostname,
// Port: port,
//}
//return addr.ToDSN()
return net.JoinHostPort(hostname, strconv.Itoa(port))
}
// ParseToAddress
/*
e.g.
("https://127.0.0.1") => "127.0.0.1:443", nil
("http://127.0.0.1:8888") => "127.0.0.1:8888", nil
("https://blog.csdn.net/weixin_52428496/article/details/110159938") => "blog.csdn.net:443", nil
*/
func ParseToAddress(str string) (*Address, error) {
tmp := strKit.TrimSpace(str)
tmp = strKit.ReplaceAll(tmp, "\\", "/")
if strKit.IsEmpty(tmp) {
return nil, errorKit.New("invalid str(%s)", str)
}
var scheme string
index := strKit.Index(tmp, "://")
if index != -1 {
scheme = strKit.SubBefore(tmp, index)
scheme = strKit.ToLower(scheme)
tmp = strKit.SubAfter(tmp, index+3)
}
index = strKit.Index(tmp, "/")
if index != -1 {
tmp = strKit.Substring(tmp, 0, index)
}
if strKit.IsEmpty(tmp) {
return nil, errorKit.New("invalid str(%s)", str)
}
arr := strKit.Split(tmp, ":")
switch len(arr) {
case 1:
hostname := arr[0]
port, err := getDefaultPortByScheme(scheme)
if err != nil {
return nil, errorKit.Wrap(err, "invalid str(%s)", str)
}
return &Address{
Hostname: hostname,
Port: port,
}, nil
case 2:
hostname := arr[0]
portStr := arr[1]
if strKit.IsAllEmpty(hostname, portStr) {
return nil, errorKit.New("invalid str(%s)", str)
}
var port int
var err error
if strKit.IsEmpty(portStr) {
port, err = getDefaultPortByScheme(scheme)
} else {
port, err = strconv.Atoi(portStr)
}
if err != nil {
return nil, errorKit.Wrap(err, "invalid str(%s)", str)
}
return &Address{
Hostname: hostname,
Port: port,
}, nil
default:
return nil, errorKit.New("invalid str(%s)", str)
}
}
func getDefaultPortByScheme(scheme string) (int, error) {
switch scheme {
case "http":
return 80, nil
case "https":
return 443, nil
default:
return -1, errorKit.New("invalid scheme(%s)", scheme)
}
}