Skip to content

Commit

Permalink
healthz, a straightforward health package
Browse files Browse the repository at this point in the history
  • Loading branch information
dimiro1 committed Nov 18, 2023
0 parents commit b006eb7
Show file tree
Hide file tree
Showing 7 changed files with 247 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Go

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build:
name: Build and Test
runs-on: ubuntu-latest

steps:
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: 'stable'

- name: Check out code
uses: actions/checkout@v2

- name: Test
run: go test -v ./...
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Binaries and object files
*.o
*.a
*.so

# Output of the go coverage tool
*.out

# IDE and editor files
.vscode/
*.swp
*.swo
*.idea/
*.DS_Store
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023 Claudemiro Alves Feitosa Neto

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.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Healthz

Healthz is a straightforward Go package for adding health check HTTP handlers to your web apps. It's ideal for
Kubernetes-like environments to ensure your service is running smoothly.

# Features

Just two functions - simple and to the point.

# Installation

Run:

```shell
go get github.com/dimiro1/healthz
```

# Usage

## Custom Health Check

```go
package main

import (
"net/http"
"github.com/dimiro1/healthz"
)

func main() {
healthCheckLogic := func() bool {
// Define your health check logic here
return true // return true if healthy, false otherwise
}

http.Handle("/healthz", healthz.Check(healthCheckLogic))
_ = http.ListenAndServe(":8080", nil)
}

```

## Always Healthy

For a basic always-healthy endpoint:

```go
package main

import (
"net/http"
"github.com/dimiro1/healthz"
)

func main() {
http.HandleFunc("/healthz", healthz.AlwaysUp)
_ = http.ListenAndServe(":8080", nil)
}

```

# LICENSE

This project is licensed under the MIT License.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/dimiro1/healthz

go 1.21
63 changes: 63 additions & 0 deletions healthz.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package healthz

import (
"fmt"
"net/http"
)

// AlwaysUp is an HTTP handler that always responds with an HTTP 200 status code,
// indicating that the application is healthy and operational. It is a convenience
// wrapper around the Handler function, pre-configured to always return a healthy status.
// This can be useful in scenarios where a simple, always-positive health check is needed,
// such as in development environments or for applications with no specific health criteria.
//
// The function internally uses Handler, passing a function that always returns true,
// to create a health check endpoint that invariably reports the application as up and running.
//
// Example usage:
//
// http.HandleFunc("/healthz", healthz.AlwaysUp)
func AlwaysUp(w http.ResponseWriter, r *http.Request) {
Check(func() bool { return true }).ServeHTTP(w, r)
}

// Check creates an HTTP handler for health check endpoints. It uses okFn,
// a custom function provided by the user, to determine the application's health.
// okFn should return true if the application is healthy, false otherwise.
//
// The handler responds with HTTP 200 (OK) if okFn returns true, indicating
// a healthy state, and with HTTP 503 (Service Unavailable) if okFn returns false,
// indicating an unhealthy state. The response includes an HTML body with a
// background color: green for healthy (200) and red for unhealthy (503).
//
// Example usage:
//
// http.Handle("/healthz", Check(func() bool {
// // Custom health check logic
// return true // or false based on health status
// }))
//
// Parameters:
// - okFn: Function returning a bool to indicate health status.
//
// Returns:
//
// An http.Handler for the health check endpoint.
func Check(okFn func() bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
color = "green"
status = http.StatusOK
)

if !okFn() {
color = "red"
status = http.StatusServiceUnavailable
}

w.Header().Set("Content-Type", "text/html")
w.WriteHeader(status)

_, _ = w.Write([]byte(fmt.Sprintf(`<!DOCTYPE html><html><body style="background-color: %s"></body></html>`, color)))
})
}
61 changes: 61 additions & 0 deletions healthz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package healthz

import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func TestAlwaysUp(t *testing.T) {
var (
w = httptest.NewRecorder()
r = httptest.NewRequest("GET", "/healthz", nil)
)

AlwaysUp(w, r)

if w.Code != http.StatusOK {
t.Errorf("HTTP Status Code expected %d, got %d", http.StatusOK, w.Code)
}

if strings.Index(w.Body.String(), "background-color: green") <= 0 {
t.Error("A green background is expected")
}
}

func TestCheck(t *testing.T) {
t.Run("Up", func(t *testing.T) {
var (
w = httptest.NewRecorder()
r = httptest.NewRequest("GET", "/healthz", nil)
)

Check(func() bool { return true }).ServeHTTP(w, r)

if w.Code != http.StatusOK {
t.Errorf("HTTP Status Code expected %d, got %d", http.StatusOK, w.Code)
}

if strings.Index(w.Body.String(), "background-color: green") <= 0 {
t.Error("A green background is expected")
}
})

t.Run("Down", func(t *testing.T) {
var (
w = httptest.NewRecorder()
r = httptest.NewRequest("GET", "/healthz", nil)
)

Check(func() bool { return false }).ServeHTTP(w, r)

if w.Code != http.StatusServiceUnavailable {
t.Errorf("HTTP Status Code expected %d, got %d", http.StatusServiceUnavailable, w.Code)
}

if strings.Index(w.Body.String(), "background-color: red") <= 0 {
t.Error("A red background is expected")
}
})
}

0 comments on commit b006eb7

Please sign in to comment.