-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
109 lines (91 loc) · 2.34 KB
/
api.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package status
import (
"encoding/json"
"net/http"
"strconv"
"time"
errs "github.com/SimonRichardson/coherence/pkg/api/http"
"github.com/SimonRichardson/coherence/pkg/cluster/farm"
"github.com/SimonRichardson/coherence/pkg/metrics"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
)
// These are the status API URL paths.
const (
APIPathLivenessQuery = "/health"
APIPathReadinessQuery = "/ready"
)
// API serves the status API
type API struct {
farm farm.Farm
logger log.Logger
clients metrics.Gauge
duration metrics.HistogramVec
errors errs.Error
}
// NewAPI creates a API with the correct dependencies.
func NewAPI(farm farm.Farm,
logger log.Logger,
clients metrics.Gauge,
duration metrics.HistogramVec,
) *API {
return &API{
farm: farm,
logger: logger,
clients: clients,
duration: duration,
errors: errs.NewError(logger),
}
}
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
level.Info(a.logger).Log("method", r.Method, "url", r.URL.String())
iw := &interceptingWriter{http.StatusOK, w}
w = iw
// Metrics
a.clients.Inc()
defer a.clients.Dec()
defer func(begin time.Time) {
a.duration.WithLabelValues(
r.Method,
r.URL.Path,
strconv.Itoa(iw.code),
).Observe(time.Since(begin).Seconds())
}(time.Now())
// Routing table
method, path := r.Method, r.URL.Path
switch {
case method == "GET" && path == APIPathLivenessQuery:
a.handleLiveness(w, r)
case method == "GET" && path == APIPathReadinessQuery:
a.handleReadiness(w, r)
default:
// Nothing found
a.errors.NotFound(w, r)
}
}
func (a *API) handleLiveness(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {
a.errors.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (a *API) handleReadiness(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if _, err := a.farm.Keys(); err == nil {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {
a.errors.Error(w, err.Error(), http.StatusInternalServerError)
}
}
type interceptingWriter struct {
code int
http.ResponseWriter
}
func (iw *interceptingWriter) WriteHeader(code int) {
iw.code = code
iw.ResponseWriter.WriteHeader(code)
}