-
Notifications
You must be signed in to change notification settings - Fork 31
/
handler.go
49 lines (42 loc) · 1.11 KB
/
handler.go
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
package http
import (
"encoding/json"
"fmt"
"net/http"
"github.com/AppsFlyer/go-sundheit"
)
const (
// ReportTypeShort is the value to be passed in the request parameter `type` when a short response is desired.
ReportTypeShort = "short"
)
// HandleHealthJSON returns an HandlerFunc that can be used as an endpoints that exposes the service health
func HandleHealthJSON(h gosundheit.Health) http.HandlerFunc {
return func(w http.ResponseWriter, request *http.Request) {
results, healthy := h.Results()
w.Header().Set("Content-Type", "application/json")
if healthy {
w.WriteHeader(200)
} else {
w.WriteHeader(503)
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", "\t")
var err error
if request.URL.Query().Get("type") == ReportTypeShort {
shortResults := make(map[string]string)
for k, v := range results {
if v.IsHealthy() {
shortResults[k] = "PASS"
} else {
shortResults[k] = "FAIL"
}
}
err = encoder.Encode(shortResults)
} else {
err = encoder.Encode(results)
}
if err != nil {
_, _ = fmt.Fprintf(w, "Failed to render results JSON: %s", err)
}
}
}