// Copyright 2026 Terin Stock // SPDX-License-Identifier: EUPL-1.2 package server import ( "cmp" "context" "errors" "log/slog" "net/http" "time" ) // HTTPServer implements a service that serves the [http.Server] returned by NewServer. type HTTPServer struct { // NewServer is called each time the HTTPServer is started. Do not return the // same instance, as an [http.Server] can not be reused after shutdown. NewServer func() *http.Server // ShutdownTimeout is the amount of time to gracefully shutdown, defaults // to 5 seconds. Should be less than the supervisor's Timeout. ShutdownTimeout *time.Duration } // Serve starts the [http.Server] returned by NewServer. The function blocks until the HTTP server // is stopped. On context cancellation the HTTP server's Shutdown method is called for a graceful // shutdown of at least ShutdownTimeout. func (s *HTTPServer) Serve(ctx context.Context) error { srv := s.NewServer() errCh := make(chan error, 1) go func() { errCh <- srv.ListenAndServe() }() select { case err := <-errCh: if errors.Is(err, http.ErrServerClosed) { return nil } return err case <-ctx.Done(): } timeout := cmp.Or(*s.ShutdownTimeout, 5*time.Second) shutdownCtx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { slog.Error("error shutting down server", "error", err) _ = srv.Close() } <-errCh return nil }