better shutdown

This commit is contained in:
$(pass /github/name)
2024-08-20 22:08:05 +02:00
parent 15d80889d1
commit 3224536e56
2 changed files with 23 additions and 12 deletions

View File

@@ -49,6 +49,10 @@ func gracefulShutdown() {
defer cancel()
// Call the server's shutdown function
server.Shutdown(ctx)
logger.Info.Println("Server gracefully stopped")
if err := server.Shutdown(ctx); err != nil {
logger.Error.Fatalf("Error during Server shutdown: %#v", err)
} else {
logger.Info.Println("Server gracefully stopped")
}
}

View File

@@ -7,6 +7,7 @@ import (
"context"
"net/http"
"path/filepath"
"time"
"GoMembership/internal/config"
"GoMembership/internal/controllers"
@@ -21,6 +22,7 @@ import (
)
var shutdownChannel = make(chan struct{})
var srv *http.Server
// Run initializes the server configuration, sets up services and controllers, and starts the HTTP server.
func Run() {
@@ -58,8 +60,12 @@ func Run() {
// accountRouter.Use(middlewares.AuthMiddleware)
logger.Info.Println("Starting server on :8080")
srv = &http.Server{
Addr: ":8080",
Handler: router,
}
go func() {
if err := http.ListenAndServe(":8080", router); err != nil && err != http.ErrServerClosed {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error.Fatalf("could not start server: %v", err)
}
}()
@@ -67,14 +73,15 @@ func Run() {
<-shutdownChannel
}
func Shutdown(ctx context.Context) {
// Signal the server to stop
close(shutdownChannel)
func Shutdown(ctx context.Context) error {
if srv == nil {
return nil
}
// Optionally wait for a timeout or other cleanup operations
// ctx can be used to manage shutdown timeout or cleanup tasks
// select {
// case <-ctx.Done():
// // handle context cancellation if needed
// }
// Graceful shutdown with a timeout
shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Attempt to shutdown the server
return srv.Shutdown(shutdownCtx)
}