package platform import ( "context" "errors" "log/slog" "net/http" "time" ) // Serve blocks until ctx is cancelled, then marks the instance as draining, // waits drainDelay for load balancers to notice and shuts down gracefully. func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration) error { return serve(ctx, log, srv, health, drainDelay, timeout, srv.ListenAndServe) } // ServeTLS is Serve for a server whose TLSConfig provides certificates. func ServeTLS(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration) error { return serve(ctx, log, srv, health, drainDelay, timeout, func() error { return srv.ListenAndServeTLS("", "") }) } func serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration, listen func() error) error { errc := make(chan error, 1) go func() { log.Info("http listening", "addr", srv.Addr, "tls", srv.TLSConfig != nil) if err := listen(); err != nil && !errors.Is(err, http.ErrServerClosed) { errc <- err } close(errc) }() select { case err := <-errc: return err case <-ctx.Done(): } health.Drain() time.Sleep(drainDelay) sctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return srv.Shutdown(sctx) } // NewHTTPServer returns a server with timeouts that bound slow clients. func NewHTTPServer(addr string, h http.Handler) *http.Server { return &http.Server{ Addr: addr, Handler: h, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, } }