Skip to content

Commit

Permalink
Merge pull request #85 from erka/shutdown-https-server
Browse files Browse the repository at this point in the history
Enable graceful shutdown for https server
  • Loading branch information
kevinmcconnell authored Jan 6, 2025
2 parents dcde7ca + eb87755 commit 202f50a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
19 changes: 17 additions & 2 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
Expand Down Expand Up @@ -57,8 +58,11 @@ func (s *Server) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()

s.commandHandler.Close()
s.httpServer.Shutdown(ctx)
PerformConcurrently(
func() { _ = s.commandHandler.Close() },
func() { s.stopHTTPServer(ctx, s.httpServer) },
func() { s.stopHTTPServer(ctx, s.httpsServer) },
)

slog.Info("Server stopped")
}
Expand Down Expand Up @@ -128,3 +132,14 @@ func (s *Server) buildHandler() http.Handler {

return handler
}

func (s *Server) stopHTTPServer(ctx context.Context, server *http.Server) {
err := server.Shutdown(ctx)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
slog.Warn("Closing active connections")
} else {
slog.Error("Error while attempting to stop server", "error", err)
}
}
}
20 changes: 20 additions & 0 deletions internal/server/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package server

import (
"sync"
)

func PerformConcurrently(fns ...func()) {
var wg sync.WaitGroup

wg.Add(len(fns))

for _, fn := range fns {
go func() {
defer wg.Done()
fn()
}()
}

wg.Wait()
}

0 comments on commit 202f50a

Please sign in to comment.