better shutdown
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user