/
api_healthcheck.go
74 lines (63 loc) · 2.16 KB
/
api_healthcheck.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
package core
import (
"fmt"
"net/http"
"strings"
"github.com/schubergphilis/mercury/pkg/healthcheck"
)
// Public API
type apiHealthCheckPublicHandler struct {
manager *Manager
}
// Public API returns the filtered json of the workers
func (h apiHealthCheckPublicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
data, err := h.manager.healthManager.JSON()
if err != nil {
apiWriteData(w, 501, apiMessage{Success: false, Data: err.Error()})
return
}
apiWriteJSONData(w, http.StatusOK, apiMessage{Success: true, Data: string(data)})
}
// Authorized personel only
type apiHealthCheckAdminHandler struct {
manager *Manager
}
// Private API returns the unfiltered json, or executes commands
func (h apiHealthCheckAdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
path := strings.Split(r.RequestURI, "/")
if len(path) < 5 {
apiWriteData(w, 405, apiMessage{Success: false, Error: "invalid request"})
}
data, err := h.manager.healthManager.JSONAuthorized(path[5])
if err != nil {
apiWriteData(w, 501, apiMessage{Success: false, Error: err.Error()})
return
}
apiWriteJSONData(w, http.StatusOK, apiMessage{Success: true, Data: string(data)})
case "POST":
// 1 2 3 4 5 6 7
// expect a url in the format: api v1 healthchecks admin UUID ACTION STATUS
// where action is the type to change, and status to what we set it
path := strings.Split(r.RequestURI, "/")
if len(path) < 7 {
apiWriteData(w, 405, apiMessage{Success: false, Error: "invalid request"})
return
}
switch path[6] {
case "status":
if _, ok := healthcheck.StringToStatusType[path[7]]; !ok {
apiWriteData(w, 501, apiMessage{Success: false, Error: fmt.Sprintf("unknown status: %s", path[7])})
return
}
err := h.manager.healthManager.SetStatus(path[5], healthcheck.StringToStatusType[path[7]])
if err != nil {
apiWriteData(w, 501, apiMessage{Success: false, Error: err.Error()})
return
}
apiWriteData(w, 200, apiMessage{Success: true})
}
apiWriteData(w, 405, apiMessage{Success: false, Error: fmt.Sprintf("unknown action: %s", path[6])})
}
}