common/health/health_server.go

48 lines
981 B
Go

package health
import (
"context"
"net/http"
"strconv"
"time"
"golang.org/x/exp/slog"
)
// HealthCheckListener runs simple http server on the specified port for
// health check probes
func HealthCheckListener(ctx context.Context, port int, log *slog.Logger) {
log.Info("Starting health listener", "port", port)
serveMux := http.NewServeMux()
serveMux.HandleFunc("/__health", basicHealth)
srv := &http.Server{
Addr: ":" + strconv.Itoa(port),
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: serveMux,
}
go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
log.Warn("health check server done listening", "err", err)
}
}()
<-ctx.Done()
if err := srv.Shutdown(ctx); err != nil {
log.Error("health check server shutdown failed", "err", err)
}
}
func basicHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
}