go 67 lines · 8 steps

Building a health check endpoint in Go

An HTTP handler pings Postgres and Redis under a timeout and reports overall service health as JSON.

Explained by highlit
1package health
2 
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "time"
8 
9 "github.com/redis/go-redis/v9"
10 "gorm.io/gorm"
11)
12 
13type Checker struct {
14 DB *gorm.DB
15 Redis *redis.Client
16}
17 
18type checkResult struct {
19 Status string `json:"status"`
20 Error string `json:"error,omitempty"`
21}
22 
23type response struct {
24 Status string `json:"status"`
25 Checks map[string]checkResult `json:"checks"`
26}
27 
28func (c *Checker) Handler(w http.ResponseWriter, r *http.Request) {
29 ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
30 defer cancel()
31 
32 resp := response{Status: "ok", Checks: map[string]checkResult{}}
33 
34 resp.Checks["postgres"] = c.pingDB(ctx)
35 resp.Checks["redis"] = c.pingRedis(ctx)
36 
37 status := http.StatusOK
38 for _, res := range resp.Checks {
39 if res.Status != "ok" {
40 resp.Status = "degraded"
41 status = http.StatusServiceUnavailable
42 break
43 }
44 }
45 
46 w.Header().Set("Content-Type", "application/json")
47 w.WriteHeader(status)
48 _ = json.NewEncoder(w).Encode(resp)
49}
50 
51func (c *Checker) pingDB(ctx context.Context) checkResult {
52 sqlDB, err := c.DB.DB()
53 if err != nil {
54 return checkResult{Status: "down", Error: err.Error()}
55 }
56 if err := sqlDB.PingContext(ctx); err != nil {
57 return checkResult{Status: "down", Error: err.Error()}
58 }
59 return checkResult{Status: "ok"}
60}
61 
62func (c *Checker) pingRedis(ctx context.Context) checkResult {
63 if err := c.Redis.Ping(ctx).Err(); err != nil {
64 return checkResult{Status: "down", Error: err.Error()}
65 }
66 return checkResult{Status: "ok"}
67}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Aggregating dependency probes into one endpoint gives orchestrators a single signal for readiness.
  2. 2Wrapping checks in a context timeout keeps a slow dependency from hanging the whole health request.
  3. 3Mapping any failed sub-check to a 503 lets load balancers route away from degraded instances.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a health check endpoint in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code