...
1
2
3
4
5 package proxy
6
7 import (
8 "context"
9 "net"
10 )
11
12
13 type ContextDialer interface {
14 DialContext(ctx context.Context, network, address string) (net.Conn, error)
15 }
16
17
18
19
20
21
22
23
24
25 func Dial(ctx context.Context, network, address string) (net.Conn, error) {
26 d := FromEnvironment()
27 if xd, ok := d.(ContextDialer); ok {
28 return xd.DialContext(ctx, network, address)
29 }
30 return dialContext(ctx, d, network, address)
31 }
32
33
34
35 func dialContext(ctx context.Context, d Dialer, network, address string) (net.Conn, error) {
36 var (
37 conn net.Conn
38 done = make(chan struct{}, 1)
39 err error
40 )
41 go func() {
42 conn, err = d.Dial(network, address)
43 close(done)
44 if conn != nil && ctx.Err() != nil {
45 conn.Close()
46 }
47 }()
48 select {
49 case <-ctx.Done():
50 err = ctx.Err()
51 case <-done:
52 }
53 return conn, err
54 }
55
View as plain text