gatus/vendor/github.com/TwiN/health
2021-11-19 23:43:24 -05:00
..
.gitattributes ⚠ Migrate TwinProduction/gatus to TwiN/gatus 2021-10-07 21:28:04 -04:00
.gitignore ⚠ Migrate TwinProduction/gatus to TwiN/gatus 2021-10-07 21:28:04 -04:00
health.go Update TwiN/health to v1.3.0 2021-11-19 23:43:24 -05:00
LICENSE.md ⚠ Migrate TwinProduction/gatus to TwiN/gatus 2021-10-07 21:28:04 -04:00
Makefile Update TwiN/health to v1.1.0 2021-11-15 20:11:13 -05:00
README.md Update TwiN/health to v1.3.0 2021-11-19 23:43:24 -05:00
status.go ⚠ Migrate TwinProduction/gatus to TwiN/gatus 2021-10-07 21:28:04 -04:00

health

build Go Report Card codecov Go version Go Reference

Health is a library used for creating a very simple health endpoint.

While implementing a health endpoint is very simple, I've grown tired of implementing it over and over again.

Installation

go get -u github.com/TwiN/health

Usage

To retrieve the handler, you must use health.Handler() and are expected to pass it to the router like so:

router := http.NewServeMux()
router.Handle("/health", health.Handler())
server := &http.Server{
    Addr:    ":8080",
    Handler: router,
}

By default, the handler will return UP when the status is down, and DOWN when the status is down. If you prefer using JSON, however, you may initialize the health handler like so:

router.Handle("/health", health.Handler().WithJSON(true))

The above will cause the response body to become {"status":"UP"} and {"status":"DOWN"} for both status respectively, unless there is a reason, in which case a reason set to because would return {"status":"UP", "reason":"because"} and {"status":"DOWN", "reason":"because"} respectively.

To change the health of the application, you can use health.SetStatus(<status>) where <status> is one health.Up or health.Down:

health.SetStatus(health.Up)
health.SetStatus(health.Down)

As for the reason:

health.SetReason("database is unreachable")

Generally speaking, you'd only want to include a reason if the status is Down, but you can do as you desire.

Complete example

package main

import (
    "net/http"
    "time"

    "github.com/TwiN/health"
)

func main() {
    router := http.NewServeMux()
    router.Handle("/health", health.Handler())
    server := &http.Server{
        Addr:         "0.0.0.0:8080",
        Handler:      router,
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
        IdleTimeout:  15 * time.Second,
    }
    server.ListenAndServe()
}