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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Aggregating dependency probes into one endpoint gives orchestrators a single signal for readiness.
- 2Wrapping checks in a context timeout keeps a slow dependency from hanging the whole health request.
- 3Mapping any failed sub-check to a 503 lets load balancers route away from degraded instances.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-health-check-endpoint-in-go-explained-go-0291/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.