gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/api/server/http/http.go (about) 1 // Package http provides a http server with features; acme, cors, etc 2 package http 3 4 import ( 5 "crypto/tls" 6 "net" 7 "net/http" 8 "os" 9 "sync" 10 11 "github.com/gorilla/handlers" 12 "gitee.com/liuxuezhan/go-micro-v1.18.0/api/server" 13 "gitee.com/liuxuezhan/go-micro-v1.18.0/util/log" 14 ) 15 16 type httpServer struct { 17 mux *http.ServeMux 18 opts server.Options 19 20 mtx sync.RWMutex 21 address string 22 exit chan chan error 23 } 24 25 func NewServer(address string) server.Server { 26 return &httpServer{ 27 opts: server.Options{}, 28 mux: http.NewServeMux(), 29 address: address, 30 exit: make(chan chan error), 31 } 32 } 33 34 func (s *httpServer) Address() string { 35 s.mtx.RLock() 36 defer s.mtx.RUnlock() 37 return s.address 38 } 39 40 func (s *httpServer) Init(opts ...server.Option) error { 41 for _, o := range opts { 42 o(&s.opts) 43 } 44 return nil 45 } 46 47 func (s *httpServer) Handle(path string, handler http.Handler) { 48 s.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler)) 49 } 50 51 func (s *httpServer) Start() error { 52 var l net.Listener 53 var err error 54 55 if s.opts.EnableACME && s.opts.ACMEProvider != nil { 56 // should we check the address to make sure its using :443? 57 l, err = s.opts.ACMEProvider.NewListener(s.opts.ACMEHosts...) 58 } else if s.opts.EnableTLS && s.opts.TLSConfig != nil { 59 l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig) 60 } else { 61 // otherwise plain listen 62 l, err = net.Listen("tcp", s.address) 63 } 64 if err != nil { 65 return err 66 } 67 68 log.Logf("HTTP API Listening on %s", l.Addr().String()) 69 70 s.mtx.Lock() 71 s.address = l.Addr().String() 72 s.mtx.Unlock() 73 74 go func() { 75 if err := http.Serve(l, s.mux); err != nil { 76 // temporary fix 77 //log.Fatal(err) 78 } 79 }() 80 81 go func() { 82 ch := <-s.exit 83 ch <- l.Close() 84 }() 85 86 return nil 87 } 88 89 func (s *httpServer) Stop() error { 90 ch := make(chan error) 91 s.exit <- ch 92 return <-ch 93 } 94 95 func (s *httpServer) String() string { 96 return "http" 97 }