-
Notifications
You must be signed in to change notification settings - Fork 4
/
src_host-name-port.go
76 lines (68 loc) · 1.59 KB
/
src_host-name-port.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
package hlfhr
import "strings"
// "[::1]:5678" => "[::1]", "5678"
func SplitHostnamePort(Host string) (hostname string, port string) {
if !strings.HasSuffix(Host, "]") {
if i := strings.LastIndexByte(Host, ':'); i != -1 {
return Host[:i], Host[i+1:]
}
}
return Host, ""
}
// "[::1]:5678" => "[::1]"
func Hostname(Host string) (hostname string) {
hostname, _ = SplitHostnamePort(Host)
return
}
// "[::1]:5678" => "5678"
func Port(Host string) (port string) {
_, port = SplitHostnamePort(Host)
return
}
// "[::1]", "5678" => "[::1]:5678"
//
// "[::1]", ":5678" => "[::1]:5678"
//
// "[::1]", "" => "[::1]"
//
// "[::1]", ":" => "[::1]"
//
// "::1" , "5678" => "[::1]:5678"
//
// "::1" , ":5678" => "[::1]:5678"
//
// "::1" , "" => "[::1]"
//
// "::1" , ":" => "[::1]"
func HostnameAppendPort(hostname string, port string) string {
if strings.Contains(hostname, ":") {
if !strings.HasPrefix(hostname, "[") {
hostname = "[" + hostname
}
if !strings.HasSuffix(hostname, "]") {
hostname += "]"
}
}
switch port {
case "", ":":
return hostname
}
if strings.HasPrefix(port, ":") {
return hostname + port
}
return hostname + ":" + port
}
// "[::1]:5678", "localhost" => "localhost:5678"
func ReplaceHostname(Host string, name string) string {
return HostnameAppendPort(name, Port(Host))
}
// "[::1]:5678", "7890" => "localhost:7890"
func ReplacePort(Host string, port string) string {
return HostnameAppendPort(Hostname(Host), port)
}
// "[::1]" => "::1"
func Ipv6CutPrefixSuffix(v6 string) string {
v6, _ = strings.CutPrefix(v6, "[")
v6, _ = strings.CutSuffix(v6, "]")
return v6
}