Skip to content

Commit

Permalink
fix: HTTP server error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
bzp2010 committed Jun 28, 2021
1 parent e0ce9d8 commit 367d174
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 21 deletions.
9 changes: 4 additions & 5 deletions api/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,15 @@ func manageAPI() error {
return err
}

err = s.Start()
if err != nil {
return err
}
// start Manager API server (with error chan for return error)
errSig := make(chan error, 1)
s.Start(errSig)

// Signal received to the process externally.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
sig := <-quit

sig := <-quit
log.Infof("The Manager API server receive %s and start shutting down", sig.String())
s.Stop()
log.Infof("The Manager API server exited")
Expand Down
20 changes: 4 additions & 16 deletions api/internal/core/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,22 @@ func NewServer(options *Options) (*server, error) {
return &server{options: options}, nil
}

func (s *server) Start() error {
func (s *server) Start(errSig chan error) {
// initialize server
err := s.init()
if err != nil {
return err
errSig <- err
}

// write daemon pid file
err = s.writePID()
if err != nil {
return err
errSig <- err
}

// print server info to stdout
s.printInfo()

// For internal error handling across multiple goroutines.
errSig := make(chan error, 1)

// start HTTP server
log.Infof("The Manager API is listening on %s", s.server.Addr)
go func() {
Expand All @@ -75,21 +72,12 @@ func (s *server) Start() error {
// start HTTPs server
if conf.SSLCert != "" && conf.SSLKey != "" {
go func() {
err := s.serverSSL.ListenAndServeTLS(conf.SSLCert, conf.SSLKey)
if err != nil && err != http.ErrServerClosed {
if err := s.serverSSL.ListenAndServeTLS(conf.SSLCert, conf.SSLKey); err != nil && err != http.ErrServerClosed {
log.Errorf("listen and serve for HTTPS failed: %s", err)
errSig <- err
}
}()
}

// handle HTTP(s) server error
select {
case err := <-errSig:
return err
default:
return nil
}
}

func (s *server) Stop() {
Expand Down

0 comments on commit 367d174

Please sign in to comment.