Created
June 8, 2016 21:29
-
-
Save tsavola/fa3ae9b03257f6bbd8bd9e2114d80f09 to your computer and use it in GitHub Desktop.
tls.DialContext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/tls" | |
"net" | |
"time" | |
) | |
func dialContextWithDialer(ctx context.Context, dialer *net.Dialer, network, addr string, config *tls.Config) (*tls.Conn, error) { | |
timeout := dialer.Timeout | |
if !dialer.Deadline.IsZero() { | |
deadlineTimeout := dialer.Deadline.Sub(time.Now()) | |
if timeout == 0 || deadlineTimeout < timeout { | |
timeout = deadlineTimeout | |
} | |
} | |
if timeout != 0 { | |
var cancel context.CancelFunc | |
ctx, cancel = context.WithTimeout(ctx, timeout) | |
defer cancel() | |
} | |
rawConn, err := dialer.DialContext(ctx, network, addr) | |
if err != nil { | |
return nil, err | |
} | |
conn := tls.Client(rawConn, config) | |
errChannel := make(chan error, 1) | |
go func() { | |
errChannel <- conn.Handshake() | |
}() | |
select { | |
case err := <-errChannel: | |
if err != nil { | |
rawConn.Close() | |
return nil, err | |
} | |
return conn, nil | |
case <-ctx.Done(): | |
return nil, ctx.Err() | |
} | |
} | |
func dialContext(ctx context.Context, network, addr string, config *tls.Config) (*tls.Conn, error) { | |
return dialContextWithDialer(ctx, new(net.Dialer), network, addr, config) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment