// KeepAlive specifies the keep-alive period for an active
// network connection.
- // If zero, keep-alives are not enabled. Network protocols
+ // If zero, keep-alives are enabled if supported by the protocol
+ // and operating system. Network protocols or operating systems
// that do not support keep-alives ignore this field.
+ // If negative, keep-alives are disabled.
KeepAlive time.Duration
// Resolver optionally specifies an alternate resolver to use.
return nil, err
}
- if tc, ok := c.(*TCPConn); ok && d.KeepAlive > 0 {
+ if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 {
setKeepAlive(tc.fd, true)
- setKeepAlivePeriod(tc.fd, d.KeepAlive)
- testHookSetKeepAlive()
+ ka := d.KeepAlive
+ if d.KeepAlive == 0 {
+ ka = 15 * time.Second
+ }
+ setKeepAlivePeriod(tc.fd, ka)
+ testHookSetKeepAlive(ka)
}
return c, nil
}
if err := ls.buildup(handler); err != nil {
t.Fatal(err)
}
- defer func() { testHookSetKeepAlive = func() {} }()
+ defer func() { testHookSetKeepAlive = func(time.Duration) {} }()
- for _, keepAlive := range []bool{false, true} {
- got := false
- testHookSetKeepAlive = func() { got = true }
- var d Dialer
- if keepAlive {
- d.KeepAlive = 30 * time.Second
- }
+ tests := []struct {
+ ka time.Duration
+ expected time.Duration
+ }{
+ {-1, -1},
+ {0, 15 * time.Second},
+ {5 * time.Second, 5 * time.Second},
+ {30 * time.Second, 30 * time.Second},
+ }
+
+ for _, test := range tests {
+ var got time.Duration = -1
+ testHookSetKeepAlive = func(d time.Duration) { got = d }
+ d := Dialer{KeepAlive: test.ka}
c, err := d.Dial("tcp", ls.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
c.Close()
- if got != keepAlive {
- t.Errorf("Dialer.KeepAlive = %v: SetKeepAlive called = %v, want %v", d.KeepAlive, got, !got)
+ if got != test.expected {
+ t.Errorf("Dialer.KeepAlive = %v: SetKeepAlive set to %v, want %v", d.KeepAlive, got, test.expected)
}
}
}
package net
-import "context"
+import (
+ "context"
+ "time"
+)
var (
// if non-nil, overrides dialTCP.
) ([]IPAddr, error) {
return fn(ctx, network, host)
}
- testHookSetKeepAlive = func() {}
+ testHookSetKeepAlive = func(time.Duration) {}
)