Add some helpers

This commit is contained in:
Frank Denis 2018-03-28 12:08:05 +02:00
parent 7f221afeff
commit 8bedb4b01e
2 changed files with 21 additions and 2 deletions

View File

@ -134,3 +134,22 @@ func ExtractPort(str string, defaultPort int) int {
}
return port
}
func StripPort(str string) string {
if idx := strings.LastIndex(str, ":"); idx >= 0 && idx < len(str)-1 {
if _, err := strconv.Atoi(str[idx+1:]); err == nil {
str = str[:idx]
}
}
return str
}
func ExtractHostAndPort(str string, defaultPort int) (host string, port int) {
host, port = str, defaultPort
if idx := strings.LastIndex(str, ":"); idx >= 0 && idx < len(str)-1 {
if portX, err := strconv.Atoi(str[idx+1:]); err == nil {
host, port = host[:idx], portX
}
}
return
}

View File

@ -74,7 +74,7 @@ func (xTransport *XTransport) rebuildTransport() {
ExpectContinueTimeout: timeout,
MaxResponseHeaderBytes: 4096,
DialContext: func(ctx context.Context, network, addrStr string) (net.Conn, error) {
host := addrStr[:strings.LastIndex(addrStr, ":")]
host, port := ExtractHostAndPort(addrStr, DefaultPort)
ipOnly := host
xTransport.cachedIPs.RLock()
cachedIP := xTransport.cachedIPs.cache[host]
@ -84,7 +84,7 @@ func (xTransport *XTransport) rebuildTransport() {
} else {
dlog.Debugf("[%s] IP address was not cached", host)
}
addrStr = ipOnly + addrStr[strings.LastIndex(addrStr, ":"):]
addrStr = ipOnly + ":" + string(port)
return dialer.DialContext(ctx, network, addrStr)
},
}