-
Notifications
You must be signed in to change notification settings - Fork 693
/
dialer.go
51 lines (44 loc) · 1.11 KB
/
dialer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package tcp
import (
"crypto/tls"
"fmt"
"net"
"time"
)
// NewDialer returns an initialized Dialer.
func NewDialer(header byte, tlsConfig *tls.Config) *Dialer {
return &Dialer{
header: header,
tlsConfig: tlsConfig,
}
}
// Dialer supports dialing a cluster service.
type Dialer struct {
header byte
tlsConfig *tls.Config
}
// Dial dials the cluster service at the given addr and returns a connection.
func (d *Dialer) Dial(addr string, timeout time.Duration) (conn net.Conn, retErr error) {
dialer := &net.Dialer{Timeout: timeout}
if d.tlsConfig == nil {
conn, retErr = dialer.Dial("tcp", addr)
} else {
conn, retErr = tls.DialWithDialer(dialer, "tcp", addr, d.tlsConfig)
}
if retErr != nil {
return nil, retErr
}
defer func() {
if retErr != nil && conn != nil {
conn.Close()
}
}()
// Write a marker byte to indicate message type.
if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
return nil, fmt.Errorf("failed to set WriteDeadline for header: %s", err.Error())
}
if _, err := conn.Write([]byte{d.header}); err != nil {
return nil, err
}
return conn, nil
}