GO · 패턴
헬스 체크 패턴
서버의 건강 상태를 점검하는 엔드포인트. Kubernetes liveness/readiness probe에 사용됩니다.
패턴중급health-checkkuberneteslivenessreadiness
핵심 설명
서버의 건강 상태를 점검하는 엔드포인트. Kubernetes liveness/readiness probe에 사용됩니다.
Go code
package main
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
)
type HealthChecker struct {
mu sync.RWMutex
checks map[string]func() error
}
func NewHealthChecker() *HealthChecker {
return &HealthChecker{checks: make(map[string]func() error)}
}
func (h *HealthChecker) Register(name string, check func() error) {
h.mu.Lock()
defer h.mu.Unlock()
h.checks[name] = check
}
func (h *HealthChecker) Handler(w http.ResponseWriter, r *http.Request) {
h.mu.RLock()
defer h.mu.RUnlock()
status := "ok"
results := map[string]string{}
for name, check := range h.checks {
if err := check(); err != nil {
status = "degraded"
results[name] = err.Error()
} else {
results[name] = "ok"
}
}
code := 200
if status != "ok" { code = 503 }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]any{
"status": status, "checks": results,
"time": time.Now().Format(time.RFC3339),
})
}
func main() {
hc := NewHealthChecker()
hc.Register("db", func() error { return nil })
hc.Register("cache", func() error { return fmt.Errorf("연결 끊김") })
mux := http.NewServeMux()
mux.HandleFunc("GET /health", hc.Handler)
fmt.Println("헬스 체크: GET /health")
}학습 팁
liveness probe는 간단하게(프로세스 생존), readiness probe는 의존성(DB, 캐시)까지 확인하세요.
주의할 점
헬스 체크에서 무거운 쿼리를 실행하면 체크 자체가 서버 성능을 저하시킵니다. 간단한 ping/pong으로 충분합니다.
자주 묻는 질문
헬스 체크 패턴란 무엇인가요?
서버의 건강 상태를 점검하는 엔드포인트. Kubernetes liveness/readiness probe에 사용됩니다.
헬스 체크 패턴 학습 시 주의할 점은 무엇인가요?
헬스 체크에서 무거운 쿼리를 실행하면 체크 자체가 서버 성능을 저하시킵니다. 간단한 ping/pong으로 충분합니다.