61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
// Package server runs the HTTP listener with the lifecycle the lab
|
|
// requires: readiness drops first, the listener stops accepting, in-flight
|
|
// requests drain within a bounded timeout, then the process exits.
|
|
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// Readiness is switched off when shutdown starts.
|
|
type Readiness interface {
|
|
SetReady(ready bool)
|
|
}
|
|
|
|
// Run serves until ctx is cancelled, then shuts down within shutdownTimeout.
|
|
func Run(ctx context.Context, log *slog.Logger, ln net.Listener, h http.Handler, ready Readiness, shutdownTimeout time.Duration) error {
|
|
srv := &http.Server{
|
|
Handler: h,
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
MaxHeaderBytes: 64 * 1024,
|
|
ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn),
|
|
}
|
|
|
|
served := make(chan error, 1)
|
|
go func() {
|
|
err := srv.Serve(ln)
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
err = nil
|
|
}
|
|
served <- err
|
|
}()
|
|
log.Info("listening", "addr", ln.Addr().String())
|
|
|
|
select {
|
|
case err := <-served:
|
|
return err
|
|
case <-ctx.Done():
|
|
}
|
|
|
|
log.Info("shutdown started", "timeout", shutdownTimeout.String())
|
|
ready.SetReady(false)
|
|
drain, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
|
defer cancel()
|
|
if err := srv.Shutdown(drain); err != nil {
|
|
log.Error("shutdown forced", "error", err.Error())
|
|
_ = srv.Close()
|
|
return err
|
|
}
|
|
<-served
|
|
log.Info("shutdown completed")
|
|
return nil
|
|
}
|