Reputation: 39
For example if the server does not respond for more than 3 seconds, I neet to get an error or something specific. I search everything but only see the lifetime of the connection (net.Dialer.Timeout / net.Dialer.Deadline) but neet to limit limit exactly the establishing time.
Now my code like
dialer := net.Dialer{LocalAddr: net.TCPAddr{IP:"192.168.1.68", Port:35030}}
conn, err := tls.DialWithDialer(dialer, "tcp", "123.45.67.89", &tls.Config{...})
Thanks!
Upvotes: 1
Views: 974
Reputation: 2393
There are many ways to do this, first, you can simply set the Timeout field of the net.Dialer
, it does what you want:
// Timeout is the maximum amount of time a dial will wait for a connect to complete. If Deadline is also set, it may fail earlier.
timeout := time.Millisecond*3000
dialer := net.Dialer{Timeout: timeout, LocalAddr: net.TCPAddr{IP:"192.168.1.68", Port:35030}}
conn, err := tls.DialWithDialer(&dialer, "tcp", "123.45.67.89", &tls.Config{...})
There are some others solutions, like using net.DialTimeout
, Dialer.DialContext and setting the timeout for the context you are passing:
timeout := time.Millisecond*3000
ctx, _ := context.WithTimeout(context.Background(), timeout)
conn , err := dialer.DialContext(ctx, "tcp", "123.45.67.89:8000")
Upvotes: 2