Skip to content

foadnh/healthcheck

Repository files navigation

Build/Test Status Test Coverage Go Report Card FOSSA Status

healthcheck

Healthcheck for Go services.

Document

pkg.go.dev

Features

  • Support background checks.
    • To protect services with expensive checks.
    • To improve response time of health check request.
  • Support threshold for number of errors in a row.
  • A Detailed format.
    • By default, response do not have body.
    • Pass detail query parameter in the request for detailed response. Good for debugging.

Motivation

Other implementations, has one of these 2 issues:

  • Don't support background checks.
  • Run a go routine per background check.

Usage

Running Service

  • Create a new ServeMux. Or use http.DefaultServeMux.
serveMux := http.NewServeMux()
  • Create a new HealthCheck instance. Pass ServeMux and healthcheck path.
h := healthcheck.New(serveMux, "/healthcheck")
  • Register as many as checks you have.
    • name: A unique name per check.
    • check: Check function.
    • timeout: Timeout of check.
    • opts: Check options. Type CheckOption. Checker Options section
h.Register("check 1", checkOne, time.Second)
h.Register("check 2", checkTwo, time.Second*10, InBackground(time.Minute*10))
  • Run it (If you don't have background checks, no need for this step). Remember to close it.
h.Run(context.Background())
defer h.Close()

Creating Checkers

A checker is a function with this signature:

type Checker func(ctx context.Context) error

Healthcheck has built-in timeouts for checks, no need to add it in checker. ctx is with a timeout, use it to release resources if needed.

Checker Options

Pass checker options when registering checks to modify the behavior.

  • InBackground forces a check to run in the background.
InBackground(interval time.Duration)
  • WithThreshold adds a threshold of errors in the row to show unhealthy state.
WithThreshold(threshold uint)

Examples

For creating new Checks, checkers package has some examples.

Executable example in pkg.go.dev.

License

This project is licensed under the terms of the Mozilla Public License 2.0.