github.com/haraldrudell/parl@v0.4.176/pnet/tcp.go (about) 1 /* 2 © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pnet 7 8 import ( 9 "net" 10 "net/http" 11 ) 12 13 type Tcp struct { 14 net.Addr // interface 15 http.ServeMux 16 http.Server 17 } 18 19 /* 20 // NewHttp creates http server host is host:port, default ":http" 21 func NewTcp(host string) (hp *Http) { 22 h := Http{ServeMux: *http.NewServeMux()} 23 h.Server.Addr = host 24 h.Server.Handler = &h.ServeMux // interface 25 return &h 26 } 27 28 const ( 29 schemeHttp = "http" 30 schemeHttps = "https" 31 ) 32 33 func (hp *Http) Run() (errCh <-chan error) { 34 errChan := make(chan error) 35 listener, err := hp.listen() 36 if err != nil { 37 panic(err) 38 } 39 go hp.run(errChan, listener) 40 return errChan 41 } 42 43 func (hp *Http) RunTLS() (errCh <-chan error) { 44 errChan := make(chan error) 45 listener, err := hp.listenTLS() 46 if err != nil { 47 panic(err) 48 } 49 go hp.run(errChan, listener) 50 return errChan 51 } 52 53 func (hp *Http) run(errCh chan<- error, listener net.Listener) { 54 defer close(errCh) 55 defer parl.Recover("", func(e error) { errCh <- e }) 56 if err := hp.Server.Serve(listener); err != nil { // blocking until Shutdown or Close 57 if err != http.ErrServerClosed { 58 errCh <- err 59 return 60 } 61 } 62 } 63 64 func (hp *Http) listen() (listener net.Listener, err error) { 65 srv := hp.Server 66 addr := srv.Addr 67 if addr == "" { 68 addr = ":http" 69 } 70 hp.mutex.Lock() 71 defer hp.mutex.Unlock() 72 if hp.Addr != nil { 73 err = error116.New("Already listening") 74 return 75 } 76 listener, err = net.Listen("tcp", addr) 77 hp.Addr = listener.Addr() 78 return 79 } 80 81 func (hp *Http) listenTLS() (listener net.Listener, err error) { 82 srv := hp.Server 83 addr := srv.Addr 84 if addr == "" { 85 addr = ":https" 86 } 87 hp.mutex.Lock() 88 defer hp.mutex.Unlock() 89 if hp.Addr != nil { 90 err = error116.New("Already listening") 91 return 92 } 93 listener, err = net.Listen("tcp", addr) 94 hp.Addr = listener.Addr() 95 return 96 } 97 98 func (hp *Http) Shutdown() (err error) { 99 return hp.Server.Shutdown(context.Background()) 100 } 101 &*/