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() defer cancel()
// Call the server's shutdown function // Call the server's shutdown function
server.Shutdown(ctx) if err := server.Shutdown(ctx); err != nil {
logger.Error.Fatalf("Error during Server shutdown: %#v", err)
} else {
logger.Info.Println("Server gracefully stopped") logger.Info.Println("Server gracefully stopped")
} }
}

View File

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