-
Notifications
You must be signed in to change notification settings - Fork 676
/
health.go
78 lines (64 loc) · 2.13 KB
/
health.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package magistrala
import (
"encoding/json"
"net/http"
)
const (
contentType = "Content-Type"
contentTypeJSON = "application/health+json"
svcStatus = "pass"
description = " service"
)
var (
// Version represents the last service git tag in git history.
// It's meant to be set using go build ldflags:
// -ldflags "-X 'github.com/absmach/magistrala.Version=0.0.0'".
Version = "0.0.0"
// Commit represents the service git commit hash.
// It's meant to be set using go build ldflags:
// -ldflags "-X 'github.com/absmach/magistrala.Commit=ffffffff'".
Commit = "ffffffff"
// BuildTime represetns the service build time.
// It's meant to be set using go build ldflags:
// -ldflags "-X 'github.com/absmach/magistrala.BuildTime=1970-01-01_00:00:00'".
BuildTime = "1970-01-01_00:00:00"
)
// HealthInfo contains version endpoint response.
type HealthInfo struct {
// Status contains service status.
Status string `json:"status"`
// Version contains current service version.
Version string `json:"version"`
// Commit represents the git hash commit.
Commit string `json:"commit"`
// Description contains service description.
Description string `json:"description"`
// BuildTime contains service build time.
BuildTime string `json:"build_time"`
// InstanceID contains the ID of the current service instance
InstanceID string `json:"instance_id"`
}
// Health exposes an HTTP handler for retrieving service health.
func Health(service, instanceID string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(contentType, contentTypeJSON)
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
res := HealthInfo{
Status: svcStatus,
Version: Version,
Commit: Commit,
Description: service + description,
BuildTime: BuildTime,
InstanceID: instanceID,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(res); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
})
}