healthcheck

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

healthcheck

Minimal framework to implement health checks for go (golang) applications on top of net/http.

CI Status Go Report Card Package Doc Releases

healthcheck provides a minimal, ultra-simple framework for implementing liveness and readyness checks for applications. The framework supports HTTP based probes with configurable readyness checks.

Installation

This module uses golang modules and can be installed with

go get github.com/halimath/healthcheck@main

It requires go >= 1.18

Usage

healthcheck provides a Handler which can be obtained using healthcheck.New. You can add Checks to that handler. Checks are executed for readyness probes but not for liveness probes. Handler satisfies http.Handler so it can be mounted to any multiplexer supporting the go standard library handler interface.

See this minimal example

h := healthcheck.New()

h.AddCheck(healthcheck.CheckURL("http://localhost:1234/"))
h.AddCheckFunc(func(ctx context.Context) error {
	// Add your check code here
	return nil
})

http.Handle("/health/", http.StripPrefix("/health", h))

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

Options

healthcheck.New accepts Options that customize the handler`s behavior. Two factory functions are provided:

  • healthcheck.WithErrorLogger lets you provide a function to log or otherwise treat any error received from a readyness check.
  • healthcheck.WithReadynessTimeout sets a timeout to apply to all readyness checks (the default is 10 seconds).

Bundled checks

URL

healthcheck supports checking URLs via HTTP GET using either healthcheck.CheckURL or healthcheck.CheckHTTPStatus. The second offers more customization. Both checks use a http.Client to query a URL and assert the received status code to be in the range 200 - 299.

sql.DB

healthcheck provides a check that executes a PingContext (defined via an interface) to ping a remote endpoint. As *sql.DB implements a PingContext function it can directly be used as a target for the healthcheck.CheckPinger function.

License

Copyright 2023 Alexander Metzner.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Overview

Package healthcheck provides types and functions to implement liveness and readyness checks based on HTTP probes. The package provides a http.Handler that can be mounted using to a running server. Client code can register checks to be executed when the readyness endpoint is invoked. The package also provides ready to use checks for HTTP endpoints and SQL databases.

The handler also reports version information of the running application. This is an opt-in feature disabled by default. The version info will be gathered using the runtime/debug and can be enhanced with custom fields.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Configures the final path element of the URL serving the liveness check.
	// Changes to this variable will only take effect when done before calling New.
	LivePath = "/livez"
	// Configures the final path element of the URL serving the readyness check.
	// Changes to this variable will only take effect when done before calling New.
	ReadyPath = "/readyz"
	// Configures the final path element of the URL serving the info endpoint.
	// Changes to this variable will only take effect when done before calling New.
	InfoPath = "/infoz"

	// Default timeout to apply to readyness checks
	DefaultReadynessCheckTimeout = 10 * time.Second
)
View Source
var ErrPingCheckFailed = errors.New("ping check failed")
View Source
var ErrURLCheckFailed = errors.New("URL check failed")

Functions

This section is empty.

Types

type Check

type Check interface {
	// Check is called to execute the check. Any non-nil return value
	// is considered a check failure incl. context deadlines.
	Check(context.Context) error
}

Check defines the interface for custom readyness checks.

func CheckHTTPResponse

func CheckHTTPResponse(method, url string, client *http.Client) Check

CheckHTTPResponse creates a Check that issues a HTTP request with method to url using client. The check reports an error if either the request fails or the received status code is >= 400 (bad request). If client is nil http.DefaultClient is used.

func CheckPing

func CheckPing(pinger Pinger) Check

CheckPing creates a Check that calls PingContext to check for connectivity. This method can directly be used on a *sql.DB.

func CheckURL

func CheckURL(url string) Check

CheckURL creates a Check that checks url for a status code < 400. The returned check uses http.DefaultClient to issue the HTTP request. Use CheckHTTPResponse when custom handling is needed.

type CheckFunc

type CheckFunc func(context.Context) error

CheckFunc is a convenience type to implement Check using a bare function.

func (CheckFunc) Check

func (f CheckFunc) Check(ctx context.Context) error

type ErrorLogger

type ErrorLogger func(err error)

ErrorLogger defines a type for a function to log errors that occured during ready check execution. err is the error returned by the check function.

type Handler

type Handler struct {
	ErrorLogger      ErrorLogger
	ReadynessTimeout time.Duration
	// contains filtered or unexported fields
}

Handler implements liveness and readyness checking.

func New

func New(opts ...Option) *Handler

New creates a new Handler ready to use. The Handler must be mounted on some HTTP path (i.e. on a http.ServeMux) to receive requests.

func (*Handler) AddCheck

func (h *Handler) AddCheck(c Check)

AddCheck registers c as another readyness check.

func (*Handler) AddCheckFunc

func (h *Handler) AddCheckFunc(c CheckFunc)

AddCheckFunc registers c as another readyness check.

func (*Handler) EnableInfo

func (h *Handler) EnableInfo(infoData map[string]any)

EnableInfo enables an info endpoint that outputs version information and additional details.

func (*Handler) ExecuteReadyChecks

func (h *Handler) ExecuteReadyChecks(ctx context.Context) error

ExecuteReadyChecks executes all readyness checks in parallel. It reports the first error hit or nil if all checks pass. Every check is executed with a timeout configured for the handler (if any).

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches and executes health checks.

type Option

type Option func(*Handler)

Option defines a function type used to customize the provided Handler.

func WithErrorLogger

func WithErrorLogger(l ErrorLogger) Option

WithErrorLogger creates an Option that sets Handler.ErrorLogger to l.

func WithReadynessTimeout

func WithReadynessTimeout(t time.Duration) Option

WithReadynessTimeout creates an Option that sets Handler.ReadynessTimeout to t.

type Pinger

type Pinger interface {
	// PingContext pings the remote endpoint. It returns nil if the endpoint is
	// healthy, a non-nil error otherwise.
	PingContext(context.Context) error
}

Pinger defines the interface for connection types that support pinging the remote endpoint to learn about its liveness. The method name is chosen to make a value of type *sql.DB satisfy this interface without any adaption.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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