forked from statping/statping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckin.go
101 lines (87 loc) · 2.14 KB
/
checkin.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
package handlers
import (
"github.com/gorilla/mux"
"github.com/statping/statping/types/checkins"
"github.com/statping/statping/types/errors"
"github.com/statping/statping/types/services"
"github.com/statping/statping/utils"
"net"
"net/http"
)
func findCheckin(r *http.Request) (*checkins.Checkin, string, error) {
vars := mux.Vars(r)
id := vars["api"]
if id == "" {
return nil, "", errors.IDMissing
}
checkin, err := checkins.FindByAPI(id)
if err != nil {
return nil, id, errors.Missing(checkins.Checkin{}, id)
}
return checkin, id, nil
}
func apiAllCheckinsHandler(w http.ResponseWriter, r *http.Request) {
returnJson(checkins.All(), w, r)
}
func apiCheckinHandler(w http.ResponseWriter, r *http.Request) {
checkin, _, err := findCheckin(r)
if err != nil {
sendErrorJson(err, w, r)
return
}
returnJson(checkin, w, r)
}
func checkinCreateHandler(w http.ResponseWriter, r *http.Request) {
var checkin *checkins.Checkin
if err := DecodeJSON(r, &checkin); err != nil {
sendErrorJson(err, w, r)
return
}
service, err := services.Find(checkin.ServiceId)
if err != nil {
sendErrorJson(err, w, r)
return
}
checkin.ServiceId = service.Id
if err := checkin.Create(); err != nil {
sendErrorJson(err, w, r)
return
}
sendJsonAction(checkin, "create", w, r)
}
func checkinHitHandler(w http.ResponseWriter, r *http.Request) {
checkin, _, err := findCheckin(r)
if err != nil {
sendErrorJson(err, w, r)
return
}
log.Infof("Checking %s was requested", checkin.Name)
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
if last := checkin.LastHit(); last == nil {
checkin.Start()
}
hit := &checkins.CheckinHit{
Checkin: checkin.Id,
From: ip,
CreatedAt: utils.Now(),
}
if err := hit.Create(); err != nil {
sendErrorJson(err, w, r)
return
}
checkin.Failing = false
checkin.LastHitTime = utils.Now()
sendJsonAction(hit.Id, "update", w, r)
}
func checkinDeleteHandler(w http.ResponseWriter, r *http.Request) {
checkin, _, err := findCheckin(r)
if err != nil {
sendErrorJson(err, w, r)
return
}
if err := checkin.Delete(); err != nil {
sendErrorJson(err, w, r)
return
}
sendJsonAction(checkin, "delete", w, r)
}