better shutdown
This commit is contained in:
@@ -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.Info.Println("Server gracefully stopped")
|
logger.Error.Fatalf("Error during Server shutdown: %#v", err)
|
||||||
|
} else {
|
||||||
|
|
||||||
|
logger.Info.Println("Server gracefully stopped")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
// Graceful shutdown with a timeout
|
||||||
// ctx can be used to manage shutdown timeout or cleanup tasks
|
shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
// select {
|
defer cancel()
|
||||||
// case <-ctx.Done():
|
|
||||||
// // handle context cancellation if needed
|
// Attempt to shutdown the server
|
||||||
// }
|
return srv.Shutdown(shutdownCtx)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user