Skip to content

Commit f6f399b

Browse files
Merge pull request #33 from Nikhils-179/fix#31
fix#31:Handle external context received by NewApp
2 parents 5695575 + 4bcf6e9 commit f6f399b

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

cmd/api/main.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,8 @@ func main() {
5151
}()
5252
}
5353

54-
app.NewApp(context.Background(), cfg).Run()
54+
if err := app.NewApp(context.Background(), cfg).Run(); err != nil {
55+
log.Print("Unable to start app")
56+
return
57+
}
5558
}

internal/app/app.go

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,33 @@ func (app *App) Run() error {
4949
<-quit
5050
log.Info("Server is shutting down...")
5151

52-
// Create a context with a timeout of 10 seconds for the server shutdown.
52+
// Create a context with a timeout to ensure graceful shutdown
5353
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
5454
defer cancel()
5555

56-
// Shutdown gracefully.
57-
app.db.DB.Close()
58-
app.echo.Shutdown(ctx)
56+
// Attempt to gracefully shutdown the Echo server
57+
if err := app.echo.Shutdown(ctx); err != nil {
58+
log.Errorf("Server shutdown failed: %v", err)
59+
} else {
60+
log.Info("Server shutdown gracefully")
61+
}
62+
63+
// Close the database connection
64+
if err := app.db.DB.Close(); err != nil {
65+
log.Errorf("Database connection close failed: %v", err)
66+
} else {
67+
log.Info("Database connection closed")
68+
}
5969
}()
6070

61-
return app.echo.Start(fmt.Sprintf(":%s", app.cfg.Server.Port))
71+
// Start the Echo server
72+
port := fmt.Sprintf(":%s", app.cfg.Server.Port)
73+
log.Infof("Server is starting on port %s", port)
74+
75+
if err := app.echo.Start(port); err != nil {
76+
log.Errorf("Error starting server: %v", err)
77+
return err
78+
}
79+
80+
return nil
6281
}

0 commit comments

Comments
 (0)