62 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-12-29 14:35:26 -05:00
package main
import (
"context"
"fmt"
2025-01-26 16:47:01 -05:00
"log/slog"
2024-12-29 14:35:26 -05:00
"net/http"
"os/signal"
"syscall"
"time"
2025-01-26 16:47:01 -05:00
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
2024-12-29 14:35:26 -05:00
"go-calc/internal/server"
)
func gracefulShutdown(apiServer *http.Server, done chan bool) {
// Create context that listens for the interrupt signal from the OS.
2025-01-26 16:47:01 -05:00
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.InfoContext(ctx.Context, msg string, args ...any), stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
2024-12-29 14:35:26 -05:00
defer stop()
// Listen for the interrupt signal.
<-ctx.Done()
2025-01-26 16:47:01 -05:00
logger.Info("shutting down gracefully, press Ctrl+C again to force")
2024-12-29 14:35:26 -05:00
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := apiServer.Shutdown(ctx); err != nil {
2025-01-26 16:47:01 -05:00
}
2024-12-29 14:35:26 -05:00
log.Println("Server exiting")
// Notify the main goroutine that the shutdown is complete
done <- true
}
func main() {
server := server.NewServer()
// Create a done channel to signal when the shutdown is complete
done := make(chan bool, 1)
// Run graceful shutdown in a separate goroutine
go gracefulShutdown(server, done)
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(fmt.Sprintf("http server error: %s", err))
}
// Wait for the graceful shutdown to complete
<-done
log.Println("Graceful shutdown complete.")
}