-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathjson_polling_sink_http.go
48 lines (42 loc) · 1.18 KB
/
json_polling_sink_http.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
package health
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
type HealthAggregationsResponse struct {
InstanceId string `json:"instance_id"`
IntervalDuration time.Duration `json:"interval_duration"`
IntervalAggregations []*IntervalAggregation `json:"aggregations"`
}
func (s *JsonPollingSink) StartServer(addr string) {
go http.ListenAndServe(addr, s)
}
func (s *JsonPollingSink) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
if r.URL.Path == "/health" {
metrics := s.GetMetrics()
response := &HealthAggregationsResponse{
InstanceId: Identifier,
IntervalDuration: s.intervalDuration,
IntervalAggregations: metrics,
}
jsonData, err := json.MarshalIndent(response, "", "\t")
if err != nil {
renderError(rw, err)
return
}
fmt.Fprintf(rw, string(jsonData))
} else {
renderNotFound(rw)
}
}
func renderNotFound(rw http.ResponseWriter) {
rw.WriteHeader(404)
fmt.Fprintf(rw, `{"error": "not_found"}`)
}
func renderError(rw http.ResponseWriter, err error) {
rw.WriteHeader(500)
fmt.Fprintf(rw, `{"error": "%s"}`, err.Error())
}