Skip to content

Health Check

package main

import (
    "log"
    "net/http"
)

type Health struct {
    Health string `json:"health"`
}

func health(wtr http.ResponseWriter, req *http.Request) {

    wtr.Header().Set("Content-Type", "application/json; charset=utf-8")
    wtr.Header().Set("X-Health-Check", "ok")
    wtr.Write([]byte(`{"health": "ok"}`))
}

func main() {
    router := http.NewServeMux()
    router.HandleFunc("/", health)

    log.Print("starting server on :8080")

    err := http.ListenAndServe(":8080", router)
    log.Fatal(err)
}

Gorilla Mux

A great getting started exercise is to begin a new web application project which starts life with health endpoint.

It's more efficient to utilize a third party package, in this case gorilla/mux which implements a request router and dispatcher for matching incoming requests to their respective handlers. The name mux stands for "HTTP request multiplexer".

Start a new project:

mkdir ~/projects/heath && cd ~/projects/heath
go mod init health.codewalker.co.uk

Install the gorilla/mux router:

go get -u github.com/gorilla/mux

Here is the most simple example:

main.go
package main

import (
    "encoding/json"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
)

func main() {

    // Define router
    router := mux.NewRouter()
    router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
        json.NewEncoder(w).Encode(map[string]bool{"ok": true})
    })

    // Configure HTTP server
    srv := &http.Server{
        Handler:      router,
        Addr:         "0.0.0.0:8080",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    // Run HTTP server
    log.Print("Starting server on 0.0.0.0:8080")
    log.Fatal(srv.ListenAndServe())
}

Now, run the application locally and test you get the expect JSON response:

go run .
curl http://localhost:8080/api/health

You can prettify the output:

curl http://localhost:8080/api/health | jq
{
  "ok": true
}