go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/keep_alive_listener.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"net"
    12  	"time"
    13  )
    14  
    15  var (
    16  	_ net.Listener = (*KeepAliveListener)(nil)
    17  )
    18  
    19  // KeepAliveListener sets TCP keep-alive timeouts on accepted
    20  // connections. It's used by ListenAndServe and ListenAndServeTLS so
    21  // dead TCP connections (e.g. closing laptop mid-download) eventually
    22  // go away.
    23  //
    24  // It is taken from net/http/server.go
    25  type KeepAliveListener struct {
    26  	*net.TCPListener
    27  
    28  	KeepAlive       bool
    29  	KeepAlivePeriod time.Duration
    30  }
    31  
    32  // Accept implements net.Listener
    33  func (ln KeepAliveListener) Accept() (c net.Conn, err error) {
    34  	tc, err := ln.AcceptTCP()
    35  	if err != nil {
    36  		return
    37  	}
    38  	_ = tc.SetKeepAlive(ln.KeepAlive)
    39  	_ = tc.SetKeepAlivePeriod(ln.KeepAlivePeriod)
    40  	return tc, nil
    41  }