healthcheck

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 7, 2026 License: MIT Imports: 7 Imported by: 0

README

healthcheck

The healthcheck package probes registered database connections and collects Go runtime diagnostics. It is intended for services that expose a /health or /readiness endpoint and need connection pool statistics, runtime memory metrics, and uptime without coupling to a specific HTTP framework.

Import

import "github.com/raykavin/gobox/healthcheck"

What it provides

  • Check for managing named database connections and producing health snapshots
  • Report() for probing all connections concurrently and collecting runtime metrics
  • CheckDB() for probing a single named connection
  • AddDB() and RemoveDB() for dynamically registering connections at runtime
  • SetPingTimeout() for overriding the per-connection ping deadline (default: 5s)
  • Pinger interface satisfied by *sql.DB out of the box, accepting any compatible type

Main types

  • Check: the main service; safe for concurrent use
  • DBEntry: named connection passed to New
  • HealthReport: full snapshot with Runtime and Databases fields
  • RuntimeReport: OS, arch, CPU count, goroutine count, uptime, and memory stats
  • DBReport: per-connection status, error, and pool counters

Example

package main

import (
    "database/sql"
    "encoding/json"
    "log"
    "net/http"

    "github.com/raykavin/gobox/healthcheck"
    _ "github.com/lib/pq"
)

func main() {
    db, err := sql.Open("postgres", "postgres://user:pass@localhost/mydb?sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }

    svc := healthcheck.New([]healthcheck.DBEntry{
        {Name: "primary", Driver: "postgres", DB: db},
    })

    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        report := svc.Report(r.Context())
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(report)
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

Example response

{
  "runtime": {
    "os": "linux",
    "arch": "amd64",
    "num_cpu": 4,
    "num_goroutine": 8,
    "uptime": "2m35s",
    "mem_allocated": 1245184,
    "mem_total_alloc": 3801088,
    "mem_sys": 10485760,
    "mem_num_gc": 3,
    "mem_last_gc": "2026-06-28T14:00:00Z"
  },
  "databases": {
    "primary": {
      "status": "healthy",
      "driver": "postgres",
      "open_connections": 5,
      "in_use": 1,
      "idle": 4,
      "wait_count": 0,
      "wait_duration": 0
    }
  }
}

Notes

  • all registered connections are probed concurrently inside Report; one slow connection does not delay others
  • each ping is bounded by pingTimeout (default 5s); use SetPingTimeout to adjust
  • AddDB and RemoveDB are safe to call while Report is in progress
  • Pinger is satisfied by *sql.DB directly; no adapter is needed for standard Go database connections
  • DBReport.Error is only populated when status is "unhealthy"

Documentation

Overview

Package healthcheck probes registered database connections and collects Go runtime diagnostics, returning a structured snapshot suitable for a health-check endpoint.

Creating the service

svc := healthcheck.New([]healthcheck.DBEntry{
    {Name: "primary", Driver: "postgres", DB: primaryDB},
    {Name: "replica", Driver: "postgres", DB: replicaDB},
})

Full report

Report probes all registered connections concurrently and returns runtime metrics alongside per-connection pool statistics.

report := svc.Report(ctx)

Single connection probe

dbReport, err := svc.CheckDB(ctx, "primary")

Dynamic registration

Connections can be added or removed at any time without restarting the service.

svc.AddDB("cache", "redis", cacheDB)
svc.RemoveDB("replica")

HTTP handler example

http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    report := svc.Report(r.Context())
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(report)
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Check

type Check struct {
	// contains filtered or unexported fields
}

Check probes registered database connections and collects Go runtime diagnostics.

func New

func New(entries []DBEntry) *Check

New creates a Check pre-loaded with the given DB entries.

func (*Check) AddDB

func (s *Check) AddDB(name, driver string, db Pinger)

AddDB registers or replaces a named connection. driver is an optional label reported in diagnostics.

func (*Check) CheckDB

func (s *Check) CheckDB(ctx context.Context, name string) (DBReport, error)

CheckDB probes a single connection by name. Returns an error if the name is not registered.

func (*Check) RemoveDB

func (s *Check) RemoveDB(name string)

RemoveDB removes a named connection.

func (*Check) Report

func (s *Check) Report(ctx context.Context) HealthReport

Report returns a full health snapshot: runtime info plus all DB probes executed concurrently.

func (*Check) SetPingTimeout

func (s *Check) SetPingTimeout(d time.Duration)

SetPingTimeout overrides the per-connection ping timeout. A non-positive value resets it to the default.

type DBEntry

type DBEntry struct {
	Name   string
	Driver string
	DB     Pinger
}

DBEntry holds a named database connection to be monitored. Driver is an optional human-readable label (e.g. "postgres", "mysql") reported back in the diagnostics; it is purely informational.

type DBReport

type DBReport struct {
	Status          string        `json:"status"`
	Driver          string        `json:"driver,omitempty"`
	Error           string        `json:"error,omitempty"`
	OpenConnections int           `json:"open_connections"`
	InUse           int           `json:"in_use"`
	Idle            int           `json:"idle"`
	WaitCount       int64         `json:"wait_count"`
	WaitDuration    time.Duration `json:"wait_duration"`
}

DBReport contains non-sensitive diagnostics for a single database connection.

type HealthReport

type HealthReport struct {
	Runtime   RuntimeReport       `json:"runtime"`
	Databases map[string]DBReport `json:"databases"`
}

HealthReport is the full snapshot returned by the service.

type Pinger

type Pinger interface {
	PingContext(ctx context.Context) error
	Stats() sql.DBStats
}

Pinger is the minimal database surface the health check needs. It is satisfied by *sql.DB out of the box, but any type implementing it (such as a test double) can be registered.

type RuntimeReport

type RuntimeReport struct {
	OS           string `json:"os"`
	Arch         string `json:"arch"`
	NumCPU       int    `json:"num_cpu"`
	NumGoroutine int    `json:"num_goroutine"`
	Uptime       string `json:"uptime"`

	// Memory (all values in bytes)
	MemAllocated  uint64 `json:"mem_allocated"`   // heap currently allocated
	MemTotalAlloc uint64 `json:"mem_total_alloc"` // cumulative heap allocated
	MemSys        uint64 `json:"mem_sys"`         // total memory from OS
	MemNumGC      uint32 `json:"mem_num_gc"`      // number of GC cycles completed
	MemLastGC     string `json:"mem_last_gc"`     // time of last GC
}

RuntimeReport contains non-sensitive Go runtime diagnostics.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL