github.com/sunvim/utils@v0.1.0/netpoll/net.go (about)

     1  // Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
     2  // This package is licensed under a MIT license that can be found in the LICENSE file.
     3  
     4  package netpoll
     5  
     6  import (
     7  	"errors"
     8  	"io"
     9  	"net"
    10  	"syscall"
    11  )
    12  
    13  const (
    14  	bufferSize = 0x10000
    15  )
    16  
    17  // EOF is the error returned by Read when no more input is available.
    18  var EOF = io.EOF
    19  
    20  // EAGAIN is the error when resource temporarily unavailable
    21  var EAGAIN = syscall.EAGAIN
    22  
    23  // ErrServerClosed is returned by the Server's Serve and ListenAndServe
    24  // methods after a call to Close.
    25  var ErrServerClosed = errors.New("Server closed")
    26  
    27  // ErrHandler is the error when the Handler is nil
    28  var ErrHandler = errors.New("Handler must be not nil")
    29  
    30  // ErrListener is the error when the Listener is nil
    31  var ErrListener = errors.New("Listener must be not nil")
    32  
    33  // ListenAndServe listens on the network address and then calls
    34  // Serve with handler to handle requests on incoming connections.
    35  //
    36  // The handler must be not nil.
    37  //
    38  // ListenAndServe always returns a non-nil error.
    39  func ListenAndServe(network, address string, handler Handler) error {
    40  	server := &Server{Network: network, Address: address, Handler: handler}
    41  	return server.ListenAndServe()
    42  }
    43  
    44  // Serve accepts incoming connections on the listener l,
    45  // and registers the conn fd to poll. The poll will trigger the fd to
    46  // read requests and then call handler to reply to them.
    47  //
    48  // The handler must be not nil.
    49  //
    50  // Serve always returns a non-nil error.
    51  func Serve(lis net.Listener, handler Handler) error {
    52  	server := &Server{Handler: handler}
    53  	return server.Serve(lis)
    54  }
    55  
    56  type netServer struct {
    57  	listener net.Listener
    58  	Handler  Handler
    59  }
    60  
    61  func (s *netServer) Serve(l net.Listener) (err error) {
    62  	s.listener = l
    63  	for {
    64  		var conn net.Conn
    65  		conn, err = s.listener.Accept()
    66  		if err != nil {
    67  			break
    68  		}
    69  		go func(c net.Conn) {
    70  			var err error
    71  			var context Context
    72  			if context, err = s.Handler.Upgrade(c); err != nil {
    73  				c.Close()
    74  				return
    75  			}
    76  			for err == nil {
    77  				err = s.Handler.Serve(context)
    78  			}
    79  			c.Close()
    80  		}(conn)
    81  	}
    82  	return
    83  }
    84  
    85  func (s *netServer) Close() error {
    86  	return s.listener.Close()
    87  }