-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
61 lines (52 loc) · 1.81 KB
/
Copy pathhandler.go
File metadata and controls
61 lines (52 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package healthcheck
import (
"encoding/json"
"net/http"
"strings"
"github.com/brpaz/go-healthcheck/v2/checks"
)
// HealthHttpResponse represents the structure of the health check HTTP response.
type HealthHttpResponse struct {
ServiceID string `json:"serviceId,omitempty"`
Description string `json:"description,omitempty"`
Version string `json:"version,omitempty"`
ReleaseID string `json:"releaseId,omitempty"`
Output string `json:"output,omitempty"`
Status checks.Status `json:"status"`
Checks map[string][]checks.Result `json:"checks"`
}
func buildOutput(checks map[string][]checks.Result) string {
var outputs []string
for checkName, results := range checks {
for _, result := range results {
if result.Output != "" {
outputs = append(outputs, checkName+": "+result.Output)
}
}
}
return strings.Join(outputs, "; ")
}
// HealthHandler provides an HTTP handler that can be used to serve the health check endpoint.
func HealthHandler(healthchecker *HealthCheck) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
w.Header().Set("Content-Type", "application/health+json")
result := healthchecker.Execute(ctx)
// Map to HTTP response structure
resp := HealthHttpResponse{
ServiceID: healthchecker.ServiceID,
Description: healthchecker.Description,
Version: healthchecker.Version,
ReleaseID: healthchecker.ReleaseID,
Status: result.Status,
Checks: result.Checks,
Output: buildOutput(result.Checks),
}
if result.Status == checks.StatusFail {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusOK)
}
_ = json.NewEncoder(w).Encode(resp)
}
}