@@ -7,6 +7,7 @@ package mysql
7
7
8
8
import (
9
9
"fmt"
10
+ "regexp"
10
11
"strconv"
11
12
"strings"
12
13
)
@@ -15,6 +16,12 @@ const (
15
16
DefaultInstancePort = 3306
16
17
)
17
18
19
+ var (
20
+ ipv4HostPortRegexp = regexp .MustCompile ("^([^:]+):([0-9]+)$" )
21
+ ipv4HostRegexp = regexp .MustCompile ("^([^:]+)$" )
22
+ ipv6HostPortRegexp = regexp .MustCompile ("^\\ [(.+)\\ ]:([0-9]+)$" ) // e.g. [2001:db8:1f70::999:de8:7648:6e8]:3308
23
+ )
24
+
18
25
// InstanceKey is an instance indicator, identified by hostname and port
19
26
type InstanceKey struct {
20
27
Hostname string
@@ -25,25 +32,33 @@ const detachHint = "//"
25
32
26
33
// ParseInstanceKey will parse an InstanceKey from a string representation such as 127.0.0.1:3306
27
34
func NewRawInstanceKey (hostPort string ) (* InstanceKey , error ) {
28
- tokens := strings .SplitN (hostPort , ":" , 2 )
29
- if len (tokens ) != 2 {
30
- return nil , fmt .Errorf ("Cannot parse InstanceKey from %s. Expected format is host:port" , hostPort )
35
+ hostname := ""
36
+ port := ""
37
+ if submatch := ipv4HostPortRegexp .FindStringSubmatch (hostPort ); len (submatch ) > 0 {
38
+ hostname = submatch [1 ]
39
+ port = submatch [2 ]
40
+ } else if submatch := ipv4HostRegexp .FindStringSubmatch (hostPort ); len (submatch ) > 0 {
41
+ hostname = submatch [1 ]
42
+ } else if submatch := ipv6HostPortRegexp .FindStringSubmatch (hostPort ); len (submatch ) > 0 {
43
+ hostname = submatch [1 ]
44
+ port = submatch [2 ]
45
+ } else {
46
+ return nil , fmt .Errorf ("Cannot parse address: %s" , hostPort )
31
47
}
32
- instanceKey := & InstanceKey {Hostname : tokens [0 ]}
33
- var err error
34
- if instanceKey .Port , err = strconv .Atoi (tokens [1 ]); err != nil {
35
- return instanceKey , fmt .Errorf ("Invalid port: %s" , tokens [1 ])
48
+ instanceKey := & InstanceKey {Hostname : hostname , Port : DefaultInstancePort }
49
+ if port != "" {
50
+ var err error
51
+ if instanceKey .Port , err = strconv .Atoi (port ); err != nil {
52
+ return instanceKey , fmt .Errorf ("Invalid port: %s" , port )
53
+ }
36
54
}
37
55
38
56
return instanceKey , nil
39
57
}
40
58
41
- // ParseRawInstanceKeyLoose will parse an InstanceKey from a string representation such as 127.0.0.1:3306.
59
+ // ParseInstanceKey will parse an InstanceKey from a string representation such as 127.0.0.1:3306.
42
60
// The port part is optional; there will be no name resolve
43
- func ParseRawInstanceKeyLoose (hostPort string ) (* InstanceKey , error ) {
44
- if ! strings .Contains (hostPort , ":" ) {
45
- return & InstanceKey {Hostname : hostPort , Port : DefaultInstancePort }, nil
46
- }
61
+ func ParseInstanceKey (hostPort string ) (* InstanceKey , error ) {
47
62
return NewRawInstanceKey (hostPort )
48
63
}
49
64
0 commit comments