Shutdown gracefully, close DB connection

This commit is contained in:
Deluan 2022-11-21 12:14:06 -05:00
parent 5f3f7afb90
commit cd41d9a419
7 changed files with 163 additions and 111 deletions

View file

@ -1,6 +1,8 @@
package server
import (
"context"
"errors"
"fmt"
"net/http"
"path"
@ -42,16 +44,40 @@ func (s *Server) MountRouter(description, urlPath string, subRouter http.Handler
var startTime = time.Now()
func (s *Server) Run(addr string) error {
func (s *Server) Run(ctx context.Context, addr string) error {
s.MountRouter("WebUI", consts.URLPathUI, s.frontendAssetsHandler())
log.Info("Navidrome server is ready!", "address", addr, "startupTime", time.Since(startTime))
server := &http.Server{
Addr: addr,
ReadHeaderTimeout: consts.ServerReadHeaderTimeout,
Handler: s.router,
}
return server.ListenAndServe()
// Start HTTP server in its own goroutine, send a signal (errC) if failed to start
errC := make(chan error)
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Error(ctx, "Could not start server. Aborting", err)
errC <- err
}
}()
log.Info(ctx, "Navidrome server is ready!", "address", addr, "startupTime", time.Since(startTime))
// Wait for a signal to terminate (or an error during startup)
select {
case err := <-errC:
return err
case <-ctx.Done():
}
// Try to stop the HTTP server gracefully
log.Info(ctx, "Stopping HTTP server")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil && !errors.Is(err, context.DeadlineExceeded) {
log.Error(ctx, "Unexpected error in http.Shutdown()", err)
}
return nil
}
func (s *Server) initRoutes() {