hc is a tiny library for synchronization of mission critical concurrent health checks
TheHealthChecker interface is a heart of this small library.
// HealthChecker represents logic of making the health check.typeHealthCheckerinterface {// Health takes the context and performs the health check.// Returns nil in case of success or an error in case// of a failure.Health(ctx context.Context)error}Let's say that we have a web application with some upstream services (database, remote storage etc.),Work of these services is critical for our application. So we need to check if they are reachable and healthy,to provide the overall service health check information to orchestrator or load balancer.
Withhc it is simple. You just need to implement theHealthChecker interface for you're downstream.
// PgUpstreamService holds logic of interaction// with Postgres database.typePgUpstreamServicestruct {db*pgxpool.Pool}func (s*PgUpstreamService)Health(ctx context.Context)error {conn,err:=s.db.Acquire(ctx)iferr!=nil {returnfmt.Errorf("unable to aquire connection from pool: %w",err) }deferconn.Release()q:=`SELECT count(*) FROM information_schema.tables WHERE table_type='public';`varcountintiferr:=conn.QueryRow(ctx,q).Scan(&count);err!=nil {returnfmt.Errorf("query failed: %w",err) }returnnil}Now in your http server health check endpoint you just need to gather information about all upstream health checks.
checker:=hc.NewMultiChecker(pgUpstream,storageUpstream)mux:=http.NewServeMux()mux.HandleFunc("/health",func(w http.ResponseWriter,r*http.Request) {iferr:=checker.Health(r.Context());err!=nil {w.WriteHeader(http.StatusServiceUnavailable)return }w.WriteHeader(http.StatusOK)})