• Stars
    star
    448
  • Rank 93,838 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created about 8 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An easy to use, extensible health check library for Go applications.

Build Status Go Report Card GoDoc

Try browsing the code on Sourcegraph!

Go Health Check

An easy to use, extensible health check library for Go applications.

New package

Use https://github.com/dimiro1/healthz for a basic health check implementation.

Table of Contents

Example

package main

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

    "github.com/dimiro1/health"
    "github.com/dimiro1/health/url"
    "github.com/dimiro1/health/db"
    "github.com/dimiro1/health/redis"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    database, _ := sql.Open("mysql", "/")
	mysql := db.NewMySQLChecker(database)
    timeout := 5 * time.Second
    
    companies := health.NewCompositeChecker()
    companies.AddChecker("Microsoft", url.NewChecker("https://www.microsoft.com/"))
    companies.AddChecker("Oracle", url.NewChecker("https://www.oracle.com/"))
    companies.AddChecker("Google", url.NewChecker("https://www.google.com/"))

    handler := health.NewHandler()
    handler.AddChecker("Go", url.NewCheckerWithTimeout("https://golang.org/", timeout))
    handler.AddChecker("Big Companies", companies)
    handler.AddChecker("MySQL", mysql)
    handler.AddChecker("Redis", redis.NewChecker("tcp", ":6379"))

    http.Handle("/health/", handler)
    http.ListenAndServe(":8080", nil)
}
$ curl localhost:8080/health/

If everything is ok the server must respond with HTTP Status 200 OK and have following json in the body.

{
    "Big Companies": {
        "Google": {
            "code": 200,
            "status": "UP"
        },
        "Microsoft": {
            "code": 200,
            "status": "UP"
        },
        "Oracle": {
            "code": 200,
            "status": "UP"
        },
        "status": "UP"
    },
    "Go": {
        "code": 200,
        "status": "UP"
    },
    "MySQL": {
        "status": "UP",
        "version": "10.1.9-MariaDB"
    },
    "Redis": {
        "status": "UP",
        "version": "3.0.5"
    },
    "status": "UP"
}

The server responds with HTTP Status 503 Service Unavailable if the ckeck is Down and the json response could be something like this.

{
    "Big Companies": {
        "Google": {
            "code": 200,
            "status": "UP"
        },
        "Microsoft": {
            "code": 200,
            "status": "UP"
        },
        "Oracle": {
            "code": 200,
            "status": "UP"
        },
        "status": "UP"
    },
    "Go": {
        "code": 200,
        "status": "UP"
    },
    "MySQL": {
        "status": "DOWN",
        "error": "Error 1044: Access denied for user ''@'localhost' to database 'invalid-database'",
    },
    "Redis": {
        "status": "UP",
        "version": "3.0.5"
    },
    "status": "DOWN"
}

Motivation

It is very important to verify the status of your system, not only the system itself, but all its dependencies, If your system is not Up you can easily know what is the cause of the problem only looking the health check.

Also it serves as a kind of basic integration test between the systems.

Inspiration

I took a lot of ideas from the spring framework.

Installation

This package is a go getable package.

$ go get github.com/dimiro1/health

API

The API is stable and I do not have any plans to break compatibility, but I recommend you to vendor this dependency in your project, as it is a good practice.

Testing

You have to install the test dependencies.

$ go get gopkg.in/DATA-DOG/go-sqlmock.v1
$ go get github.com/rafaeljusto/redigomock

or you can go get this package with the -t flag

go get -t github.com/dimiro1/health

Implementing custom checkers

The key interface is health.Checker, you only have to implement a type that satisfies that interface.

type Checker interface {
	Check() Health
}

Here is an example of Disk Space usage (unix only).

package main

import (
    "syscall"
    "os"
)

type DiskSpaceChecker struct {
	Dir       string
	Threshold uint64
}

func NewDiskSpaceChecker(dir string, threshold uint64) DiskSpaceChecker {
	return DiskSpaceChecker{Dir: dir, Threshold: threshold}
}

func (d DiskSpaceChecker) Check() health.Health {
	health := health.NewHealth()

	var stat syscall.Statfs_t

	wd, err := os.Getwd()

	if err != nil {
        health.Down().AddInfo("error", err.Error()) // Why the check is Down
        return health
	}

	syscall.Statfs(wd, &stat)

	diskFreeInBytes := stat.Bavail * uint64(stat.Bsize)

	if diskFreeInBytes < d.Threshold {
		health.Down()
	} else {
        health.Up()
    }

    health.
        AddInfo("free", diskFreeInBytes).
        AddInfo("threshold", d.Threshold)

	return health
}

Important

The status key in the json has priority over a status key added by a Checker, so if some checker adds a status key to the json, it will not be rendered

Implemented health check indicators

Health Description Package
url.Checker Check the connection with some URL https://github.com/dimiro1/health/tree/master/url
db.Checker Check the connection with the database https://github.com/dimiro1/health/tree/master/db
redis.Checker Check the connection with the redis https://github.com/dimiro1/health/tree/master/redis

LICENSE

The MIT License (MIT)

Copyright (c) 2016 Claudemiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

banner

An easy way to add useful startup banners into your Go applications
Go
443
star
2

ipe

An open source Pusher server implementation compatible with Pusher client libraries written in GO
Go
367
star
3

gopong

HTML5 Pong implementation in GO
Go
36
star
4

lambda-wkhtmltopdf

Convert HTML to PDF using wkhtmltopdf on AWS Lambda
JavaScript
18
star
5

Z80-js

A Z80 emulator implemented in Typescript/Javascript
JavaScript
17
star
6

aws-serverlerss-go

How to use standard HTTP library with the new Golang official AWS lambda runtime.
Go
8
star
7

faker

A package that generates fake data for GO
Go
7
star
8

experiments

Collection of programming experiments
Go
7
star
9

reply

Library to trim replies from plain text email. (Golang port of https://github.com/discourse/email_reply_trimmer)
Go
5
star
10

GameBoyCPP

A GameBoy Emulator written in C++
C++
4
star
11

x-example

Example for https://github.com/dimiro1/x
Go
3
star
12

mixpanel-aws-lambda

JavaScript
2
star
13

vimfiles

my vim configuration
Vim Script
2
star
14

x

X is a set of modules that make creating HTTP servers fun again
Go
2
star
15

thrift-clojure-example

Implementation of the Thrift Servlet with Clojure Ring/compojure.
Clojure
2
star
16

z80-cpu

Automatically exported from code.google.com/p/z80-cpu
Java
2
star
17

hackvm

nand2tetris HackVM implemented in Go
Go
2
star
18

sense

Extract meaning from HTML pages
Kotlin
2
star
19

go-lambda

Golang Hello World Lambda With API Gateway and Serverless
Go
2
star
20

cookbook

Golang Cookbook
1
star
21

.emacs.d

My Emacs config
Emacs Lisp
1
star
22

jschip8

Javascript Chip8 Emulator
JavaScript
1
star
23

mynes

A Work in Progress NES Emulator
Java
1
star
24

ramaze-rubinius

Ruby
1
star
25

example

Go
1
star
26

gochip8

A chip8 emulator in GO
Go
1
star
27

sameForm

Your form with the same nice look in all browsers.
JavaScript
1
star
28

graphql-api

GraphQL API implementation Golang
Go
1
star
29

bogus

Fake HTTP Server
Go
1
star
30

avaz-sample-backend-frontend-auth

Very simple application that shows how to deal with user authentication with React.
JavaScript
1
star
31

GraficoAFN

Trabalho de computação gráfica e Linguagens Formais
C++
1
star
32

gettitle

Amazon AWS Lambda compatible page get title service.
Java
1
star
33

toggle

A Go feature switch library
Go
1
star
34

todos-sample

Sample Application using gorm and database/sql
Go
1
star
35

healthz

Straightforward health package
Go
1
star
36

guia_mais_js

JavaScript
1
star