|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "os/signal" |
| 9 | + "syscall" |
| 10 | + "time" |
| 11 | + |
| 12 | + "bluepront-ui/internal/server" |
| 13 | +) |
| 14 | + |
| 15 | +func gracefulShutdown(apiServer *http.Server, done chan bool) { |
| 16 | + // Create context that listens for the interrupt signal from the OS. |
| 17 | + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) |
| 18 | + defer stop() |
| 19 | + |
| 20 | + // Listen for the interrupt signal. |
| 21 | + <-ctx.Done() |
| 22 | + |
| 23 | + log.Println("shutting down gracefully, press Ctrl+C again to force") |
| 24 | + |
| 25 | + // The context is used to inform the server it has 5 seconds to finish |
| 26 | + // the request it is currently handling |
| 27 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 28 | + defer cancel() |
| 29 | + if err := apiServer.Shutdown(ctx); err != nil { |
| 30 | + log.Printf("Server forced to shutdown with error: %v", err) |
| 31 | + } |
| 32 | + |
| 33 | + log.Println("Server exiting") |
| 34 | + |
| 35 | + // Notify the main goroutine that the shutdown is complete |
| 36 | + done <- true |
| 37 | +} |
| 38 | + |
| 39 | +func main() { |
| 40 | + |
| 41 | + server := server.NewServer() |
| 42 | + |
| 43 | + // Create a done channel to signal when the shutdown is complete |
| 44 | + done := make(chan bool, 1) |
| 45 | + |
| 46 | + // Run graceful shutdown in a separate goroutine |
| 47 | + go gracefulShutdown(server, done) |
| 48 | + |
| 49 | + err := server.ListenAndServe() |
| 50 | + if err != nil && err != http.ErrServerClosed { |
| 51 | + panic(fmt.Sprintf("http server error: %s", err)) |
| 52 | + } |
| 53 | + |
| 54 | + // Wait for the graceful shutdown to complete |
| 55 | + <-done |
| 56 | + log.Println("Graceful shutdown complete.") |
| 57 | +} |
0 commit comments