healthcheck

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 20, 2021 License: MIT Imports: 6 Imported by: 0

README

Healthcheck

Build Status Go Report Card GoDoc codecov FOSSA Status

Note: This is a fork of etherlabsio/healthcheck with some changes that allow the health checkers to be easily used outside of HTTP servers, but also, in HTTP servers the error responses can be customised. This fork is not compatible with the original code.

A simple and extensible RESTful Healthcheck API implementation for Go services.

Health provides an http.Handlefunc for use as a healthcheck endpoint used by external services or load balancers. The function is used to determine the health of the application and to remove unhealthy application hosts or containers from rotation.

Instead of blindly returning a 200 HTTP status code, a healthcheck endpoint should test all the mandatory dependencies that are essential for proper functioning of a web service.

Implementing the Checker interface and passing it on to healthcheck allows you to test the the dependencies such as a database connection, caches, files and even external services you rely on. You may choose to not fail the healthcheck on failure of certain dependencies such as external services that you are not always dependent on.

Example

Without HTTP servers
package main

import (
	"context"
	"database/sql"
	"fmt"
	"net/http"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
	"github.com/hoshsadiq/go-healthcheck"
	"github.com/hoshsadiq/go-healthcheck/checkers"
)

func main() {
	// For brevity, error check is being omitted here.
	db, _ := sql.Open("mysql", "user:password@/dbname")
	defer db.Close()

	svc := healthcheck.NewService(

		// WithTimeout allows you to set a max overall timeout.
		healthcheck.WithTimeout(5*time.Second),

		// Checkers fail the status in case of any error.
		healthcheck.WithChecker(
			"heartbeat", checkers.Heartbeat("$PROJECT_PATH/heartbeat"),
		),

		healthcheck.WithChecker(
			"database", healthcheck.CheckerFunc(
				func(ctx context.Context) error {
					return db.PingContext(ctx)
				},
			),
		),

		// Observers do not fail the status in case of error.
		healthcheck.WithObserver(
			"diskspace", checkers.DiskSpace("/var/log", 90),
		),
	)

	errorCode, errorMessages := svc.CheckHealth(context.Background())
	fmt.Println(errorCode)
	fmt.Println(errorMessages)

	// this can also with a HTTP server
	r := mux.NewRouter()
	r.handle("/healthcheck", svc.Handler())
	// alternatively you can customise the error message
	r.handle("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
		errorCode, errorMessages := svc.CheckHealth(context.Background())
		// do something with errorCode and errorMessages
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(errorCode)
		json.NewEncoder(w).Encode(errorMessages)
	})
	http.ListenAndServe(":8080", r)
}

Based on the example provided above, curl localhost:8080/healthcheck | jq should yield on error a response with an HTTP statusCode of 503.

{
  "status": "Service Unavailable",
  "errors": {
    "database": "dial tcp 127.0.0.1:3306: getsockopt: connection refused",
    "heartbeat": "heartbeat not found. application should be out of rotation"
  }
}

License

This project is licensed under the terms of the MIT license. See the LICENSE file.

Documentation

Overview

Package healthcheck provides a health check service that allows to easily test if services are alive.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Checker

type Checker interface {
	Check(ctx context.Context) error
}

Checker checks the status of the dependency and returns error. In case the dependency is working as expected, return nil.

type CheckerFunc

type CheckerFunc func(ctx context.Context) error

CheckerFunc is a convenience type to create functions that implement the Checker interface.

func (CheckerFunc) Check

func (c CheckerFunc) Check(ctx context.Context) error

Check Implements the Checker interface to allow for any func() error method to be passed as a Checker.

type Option

type Option func(*health)

Option adds optional parameter for the Healthcheck.

func WithChecker

func WithChecker(name string, s Checker) Option

WithChecker adds a status checker that needs to be added as part of healthcheck. i.e database, cache or any external dependency.

func WithObserver

func WithObserver(name string, s Checker) Option

WithObserver adds a status checker but it does not fail the entire status.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout configures the global timeout for all individual checkers.

type Service

type Service interface {
	CheckHealth(ctx context.Context) (httpError int, errorMsgs map[string]string)
	Handler() http.Handler
	HandlerFunc() http.HandlerFunc
}

Service contains a health check service that can be used to check the health of multiple services.

func NewService

func NewService(opts ...Option) Service

NewService returns a new Service instance.

Directories

Path Synopsis
Package checkers adds some basic checkers for the package healthcheck.
Package checkers adds some basic checkers for the package healthcheck.

Jump to

Keyboard shortcuts

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