all: Use context in lib/dialer (#6177)

* all: Use context in lib/dialer

* a bit slimmer

* https://github.com/syncthing/syncthing/pull/5753

* bot

* missed adding debug.go

* errors.Cause

* simultaneous dialing

* anti-leak
This commit is contained in:
Simon Frei
2019-11-26 08:39:51 +01:00
committed by Audrius Butkevicius
parent 4e151d380c
commit 1bae4b7f50
24 changed files with 175 additions and 204 deletions

View File

@@ -7,6 +7,7 @@
package osutil
import (
"context"
"net/url"
"time"
@@ -16,9 +17,11 @@ import (
// TCPPing returns the duration required to establish a TCP connection
// to the given host. ICMP packets require root privileges, hence why we use
// tcp.
func TCPPing(address string) (time.Duration, error) {
func TCPPing(ctx context.Context, address string) (time.Duration, error) {
start := time.Now()
conn, err := dialer.DialTimeout("tcp", address, time.Second)
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
conn, err := dialer.DialContext(ctx, "tcp", address)
if conn != nil {
conn.Close()
}
@@ -27,11 +30,11 @@ func TCPPing(address string) (time.Duration, error) {
// GetLatencyForURL parses the given URL, tries opening a TCP connection to it
// and returns the time it took to establish the connection.
func GetLatencyForURL(addr string) (time.Duration, error) {
func GetLatencyForURL(ctx context.Context, addr string) (time.Duration, error) {
uri, err := url.Parse(addr)
if err != nil {
return 0, err
}
return TCPPing(uri.Host)
return TCPPing(ctx, uri.Host)
}