Skip to content

Commit

Permalink
enable TCP keep-alives
Browse files Browse the repository at this point in the history
  • Loading branch information
bslizon authored and kirillDanshin committed Sep 27, 2018
1 parent be257bc commit 2e04bb8
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1230,15 +1230,38 @@ func (ctx *RequestCtx) TimeoutErrorWithResponse(resp *Response) {
ctx.timeoutResponse = respCopy
}

// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe, ListenAndServeTLS and
// ListenAndServeTLSEmbed so dead TCP connections (e.g. closing laptop mid-download)
// eventually go away.
type tcpKeepAliveListener struct {
*net.TCPListener
}

func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
tc, err := ln.AcceptTCP()
if err != nil {
return nil, err
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}

// ListenAndServe serves HTTP requests from the given TCP4 addr.
//
// Pass custom listener to Serve if you need listening on non-TCP4 media
// such as IPv6.
//
// Accepted connections are configured to enable TCP keep-alives.
func (s *Server) ListenAndServe(addr string) error {
ln, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
if tcpln, ok := ln.(*net.TCPListener); ok {
return s.Serve(tcpKeepAliveListener{tcpln})
}
return s.Serve(ln)
}

Expand Down Expand Up @@ -1270,11 +1293,16 @@ func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error {
//
// If the certFile or keyFile has not been provided to the server structure,
// the function will use the previously added TLS configuration.
//
// Accepted connections are configured to enable TCP keep-alives.
func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
ln, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
if tcpln, ok := ln.(*net.TCPListener); ok {
return s.ServeTLS(tcpKeepAliveListener{tcpln}, certFile, keyFile)
}
return s.ServeTLS(ln, certFile, keyFile)
}

Expand All @@ -1287,11 +1315,16 @@ func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
//
// If the certFile or keyFile has not been provided the server structure,
// the function will use previously added TLS configuration.
//
// Accepted connections are configured to enable TCP keep-alives.
func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error {
ln, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
if tcpln, ok := ln.(*net.TCPListener); ok {
return s.ServeTLSEmbed(tcpKeepAliveListener{tcpln}, certData, keyData)
}
return s.ServeTLSEmbed(ln, certData, keyData)
}

Expand Down

0 comments on commit 2e04bb8

Please sign in to comment.