Documentation
¶
Overview ¶
Package health contains health checking utilities.
The most interesting part of the API is Register (and RegisterFunc), which is a simple way to set up a health check for ‘anything’.
As soon as any health checks are registered a summary of them is served at http://0.0.0.0:9999.
For services there is `HealthCheckCommand()` to put (early) in `main()`, e.g:
if len(os.Args) >= 2 && os.Args[1] == "healthcheck" {
health.Main()
}
Docker images can then use the following:
HEALTHCHECK --interval=10s --timeout=30s CMD ./app healthcheck
See <https://inadarei.github.io/rfc-healthcheck/>.
Example ¶
package main
import (
"context"
"github.com/dotse/go-health"
)
func main() {
ctx := context.Background()
// Register an instance of some type that implements HealthChecker:
m := new(MyTypeWithHealthCheck)
health.Register(ctx, "mytype", m)
// Register a function:
r := health.RegisterFunc(ctx, "func", func(context.Context) (checks []health.Check) {
// Checkers can return any number of checks.
for range 3 {
var check health.Check
// Make the relevant changes to `check` here, most importantly
// `check.Status`.
checks = append(checks, check)
}
return checks
})
defer r.Deregister()
}
type MyTypeWithHealthCheck struct{}
func (*MyTypeWithHealthCheck) CheckHealth(context.Context) []health.Check {
return []health.Check{{}}
}
Output:
Index ¶
- Constants
- func DeregisterAll()
- func HandleHTTP(w http.ResponseWriter, req *http.Request)
- func Main(ctx context.Context)
- func StartServer(ctx context.Context) error
- type Check
- type Checker
- type CheckerFunc
- type Option
- type Registered
- func Register(ctx context.Context, name string, checker Checker) Registered
- func RegisterFunc(ctx context.Context, name string, f func(context.Context) []Check) Registered
- func RegisterSQLConn(ctx context.Context, conn *sql.Conn, name string, base Check) Registered
- func RegisterSQLDB(ctx context.Context, db *sql.DB, name string, base Check) Registered
- type Response
- type Status
Examples ¶
Constants ¶
const ( // ExitErr is the exit code on failure. ExitErr = 1 // ExitUser is the exit code when the user did something wrong. ExitUser = 2 )
const ( // ComponentTypeComponent is ‘component’. ComponentTypeComponent = "component" // ComponentTypeDatastore is ‘datastore’. ComponentTypeDatastore = "datastore" // ComponentTypeSystem is ‘system’. ComponentTypeSystem = "system" )
const ( // ContentType is the media (MIME) type returned by the server. ContentType = "application/health+json" // EnvHealthPort is ‘HEALTH_PORT’; the environment variable to configure the // health check HTTP port. EnvHealthPort = "HEALTH_PORT" )
Variables ¶
This section is empty.
Functions ¶
func DeregisterAll ¶ added in v0.4.0
func DeregisterAll()
DeregisterAll removes all previously registered health checkers.
func HandleHTTP ¶ added in v0.3.0
func HandleHTTP(w http.ResponseWriter, req *http.Request)
HandleHTTP serves a health response over HTTP. It supports the GET, HEAD and OPTIONS methods as well as content negotiation.
func Main ¶ added in v0.3.0
Main is a utility for services that exits the current process with 0 or 1 for a healthy or unhealthy state, respectively.
func StartServer ¶ added in v0.3.0
StartServer starts an HTTP server at 0.0.0.0:${HEALTH_PORT:-9999} serving health checks. Can be called multiple times but will only start one server.
Will block until the server is listening.
The server will be stopped when the passed context.Context is cancelled.
Types ¶
type Check ¶
type Check struct {
ComponentID string `json:"componentId,omitempty"`
ComponentType string `json:"componentType,omitempty"`
ObservedValue any `json:"observedValue,omitempty"`
ObservedUnit string `json:"observedUnit,omitempty"`
Status Status `json:"status"`
AffectedEndpoints []string `json:"affectedEndpoints,omitempty"`
Time *time.Time `json:"time,omitempty"`
Output string `json:"output,omitempty"`
Links []string `json:"links,omitempty"`
}
Check represent a single health check point.
func (*Check) SetObservedTime ¶
SetObservedTime sets the observedValue field to a time duration (and the observedUnit field to the correct unit).
type CheckerFunc ¶ added in v0.3.0
CheckerFunc is a wrapper for a function that implements Checker.
func (CheckerFunc) CheckHealth ¶ added in v0.3.0
func (f CheckerFunc) CheckHealth(ctx context.Context) []Check
CheckHealth implements Checker by calling the CheckerFunc.
func (CheckerFunc) LogValue ¶ added in v0.3.0
func (f CheckerFunc) LogValue() slog.Value
type Option ¶ added in v0.3.0
type Option interface {
// contains filtered or unexported methods
}
Option is an optional configuration for CheckHealth.
func WithHost ¶ added in v0.3.0
WithHost is an Option for CheckHealth to specify the host.
func WithPort ¶ added in v0.3.0
WithPort is an Option for CheckHealth to specify the port number.
func WithTimeout ¶ added in v0.3.0
WithTimeout is an Option for CheckHealth to specify a timeout. See net/http.Client.Timeout.
type Registered ¶
type Registered struct {
// contains filtered or unexported fields
}
Registered is returned when registering a health check. It can be used to deregister that particular check at a later time, e.g. when closing whatever is being checked.
func Register ¶
func Register(ctx context.Context, name string, checker Checker) Registered
Register registers a health checker.
func RegisterFunc ¶
RegisterFunc registers a health check function.
func RegisterSQLConn ¶ added in v0.3.0
func RegisterSQLDB ¶ added in v0.3.0
func (Registered) Deregister ¶
func (r Registered) Deregister()
Deregister removes a previously registered health checker.
type Response ¶
type Response struct {
Status Status `json:"status"`
Version string `json:"version,omitempty"`
ReleaseID string `json:"releaseId,omitempty"`
Notes []string `json:"notes,omitempty"`
Output string `json:"output,omitempty"`
Checks map[string][]Check `json:"checks,omitempty"`
Links []string `json:"links,omitempty"`
ServiceID string `json:"serviceID,omitempty"`
Description string `json:"description,omitempty"`
}
Response represents a health check response, containing any number of Checks.
func CheckHealth ¶
CheckHealth gets a Response from an HTTP server.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/dotse/go-health"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// The server can be started before registering…
if err := health.StartServer(ctx); err != nil {
panic(err)
}
// Set up a checker so that there’s something to report.
r := health.RegisterFunc(ctx, "example", func(context.Context) []health.Check {
return []health.Check{{
Status: health.StatusPass,
Output: "all good",
}}
})
defer r.Deregister()
// …or after. (Subsequent StartServer()s do nothing.)
if err := health.StartServer(ctx); err != nil {
panic(err)
}
// Get the current health status of a server running at localhost. More
// configuration is possible.
resp, err := health.CheckHealth(ctx, health.WithTimeout(time.Minute))
if resp == nil || err != nil {
panic(err)
}
fmt.Printf(
`
resp.Status: %q
resp.Checks["example"][0].Status: %q
resp.Checks["example"][0].Output: %q
err: %v
`,
resp.Status,
resp.Checks["example"][0].Status,
resp.Checks["example"][0].Output,
err,
)
}
Output: resp.Status: "pass" resp.Checks["example"][0].Status: "pass" resp.Checks["example"][0].Output: "all good" err: <nil>
func CheckNow ¶ added in v0.3.0
CheckNow returns the current (local) health status accumulated from all registered health checkers.
func ReadResponse ¶
ReadResponse reads a JSON Response from an io.Reader.
func (*Response) AddChecks ¶
AddChecks adds Checks to a Response and sets the status of the Response to the ‘worst’ status.
type Status ¶
type Status uint8
Status is the status part of a Response or Check.
func WorstStatus ¶
WorstStatus returns the worst of a number of statuses, where ‘warn’ is worse than ‘pass’ but ‘fail’ is worse than ‘warn’.
func (Status) MarshalJSON ¶
MarshalJSON encodes a status as a JSON string.
func (Status) MarshalText ¶
MarshalText encodes a status as a string.
func (*Status) UnmarshalJSON ¶
UnmarshalJSON decodes a status from a JSON string.