Skip to content

Commit 1905c46

Browse files
fhoemersion
authored andcommitted
imapclient: make net.Dialer configurable
The default 30s dial timeout is too short for slow IMAP servers. When I connect to my provider's server, I often have to retry multiple times until no context deadline error happens. Make the dial timeout configurable by adding a Dialer field to the Options struct.
1 parent 191dd53 commit 1905c46

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

imapclient/client.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,9 @@ const (
4545

4646
cmdWriteTimeout = 30 * time.Second
4747
literalWriteTimeout = 5 * time.Minute
48-
)
4948

50-
var dialer = &net.Dialer{
51-
Timeout: 30 * time.Second,
52-
}
49+
defaultDialTimeout = 30 * time.Second
50+
)
5351

5452
// SelectedMailbox contains metadata for the currently selected mailbox.
5553
type SelectedMailbox struct {
@@ -77,6 +75,9 @@ type Options struct {
7775
UnilateralDataHandler *UnilateralDataHandler
7876
// Decoder for RFC 2047 words.
7977
WordDecoder *mime.WordDecoder
78+
// Dialer to use when establishing connections with the Dial* functions.
79+
// If nil, a default dialer with a 30 second timeout is used.
80+
Dialer *net.Dialer
8081
}
8182

8283
func (options *Options) wrapReadWriter(rw io.ReadWriter) io.ReadWriter {
@@ -119,6 +120,13 @@ func (options *Options) tlsConfig() *tls.Config {
119120
}
120121
}
121122

123+
func (options *Options) dialer() *net.Dialer {
124+
if options.Dialer == nil {
125+
return &net.Dialer{Timeout: defaultDialTimeout}
126+
}
127+
return options.Dialer
128+
}
129+
122130
// Client is an IMAP client.
123131
//
124132
// IMAP commands are exposed as methods. These methods will block until the
@@ -212,7 +220,7 @@ func NewStartTLS(conn net.Conn, options *Options) (*Client, error) {
212220

213221
// DialInsecure connects to an IMAP server without any encryption at all.
214222
func DialInsecure(address string, options *Options) (*Client, error) {
215-
conn, err := dialer.Dial("tcp", address)
223+
conn, err := options.dialer().Dial("tcp", address)
216224
if err != nil {
217225
return nil, err
218226
}
@@ -226,6 +234,7 @@ func DialTLS(address string, options *Options) (*Client, error) {
226234
tlsConfig.NextProtos = []string{"imap"}
227235
}
228236

237+
dialer := options.dialer()
229238
conn, err := tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
230239
if err != nil {
231240
return nil, err
@@ -244,7 +253,7 @@ func DialStartTLS(address string, options *Options) (*Client, error) {
244253
return nil, err
245254
}
246255

247-
conn, err := dialer.Dial("tcp", address)
256+
conn, err := options.dialer().Dial("tcp", address)
248257
if err != nil {
249258
return nil, err
250259
}

0 commit comments

Comments
 (0)