github.com/sunvim/utils@v0.1.0/netpoll/net_other.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 //go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd 5 // +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd 6 7 package netpoll 8 9 import ( 10 "errors" 11 "net" 12 "sync/atomic" 13 ) 14 15 // Server defines parameters for running a server. 16 type Server struct { 17 Network string 18 Address string 19 // Handler responds to a single request. 20 Handler Handler 21 // NoAsync do not work for consisted with other system. 22 NoAsync bool 23 // UnsharedWorkers do not work for consisted with other system. 24 UnsharedWorkers int 25 // SharedWorkers do not work for consisted with other system. 26 SharedWorkers int 27 // TasksPerWorker do not work for consisted with other system. 28 TasksPerWorker int 29 netServer *netServer 30 closed int32 31 } 32 33 // ListenAndServe listens on the network address and then calls 34 // Serve with handler to handle requests on incoming connections. 35 // 36 // ListenAndServe always returns a non-nil error. 37 // After Close the returned error is ErrServerClosed. 38 func (s *Server) ListenAndServe() error { 39 if atomic.LoadInt32(&s.closed) != 0 { 40 return ErrServerClosed 41 } 42 ln, err := net.Listen(s.Network, s.Address) 43 if err != nil { 44 return err 45 } 46 return s.Serve(ln) 47 } 48 49 // Serve accepts incoming connections on the listener l, 50 // and registers the conn fd to poll. The poll will trigger the fd to 51 // read requests and then call handler to reply to them. 52 // 53 // Serve always returns a non-nil error. 54 // After Close the returned error is ErrServerClosed. 55 func (s *Server) Serve(l net.Listener) (err error) { 56 if l == nil { 57 return ErrListener 58 } 59 if s.Handler == nil { 60 return ErrHandler 61 } 62 if atomic.LoadInt32(&s.closed) != 0 { 63 return ErrServerClosed 64 } 65 s.netServer = &netServer{Handler: s.Handler} 66 return s.netServer.Serve(l) 67 } 68 69 // Close closes the server. 70 func (s *Server) Close() error { 71 if !atomic.CompareAndSwapInt32(&s.closed, 0, 1) { 72 return nil 73 } 74 return s.netServer.Close() 75 }