-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpatrol_http_api.go
92 lines (90 loc) · 1.83 KB
/
patrol_http_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
package patrol
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
)
func (self *Patrol) ServeHTTPAPI(
w http.ResponseWriter,
r *http.Request,
) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if r.Method != "POST" &&
r.Method != "GET" {
// unknown method
w.WriteHeader(405)
bs, _ := json.MarshalIndent(
&API_Response{
Errors: []string{
"Invalid Method",
},
},
"", "\t",
)
w.Write(bs)
w.Write([]byte("\n"))
return
}
request := &API_Request{}
if r.Method == "GET" {
// regular API GET - we're using a query string here
// we only support returning a response, no modifications
q := r.URL.Query()
request.ID = q.Get("id")
request.Group = q.Get("group")
if toggle, _ := strconv.ParseUint(q.Get("toggle"), 10, 64); toggle > 0 {
request.Toggle = uint8(toggle)
}
request.History = len(q["history"]) > 0
request.Secret = q.Get("secret")
if cas, _ := strconv.ParseUint(q.Get("cas"), 10, 64); cas > 0 {
request.CAS = cas
}
} else {
// POST
// read request
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(400)
bs, _ := json.MarshalIndent(
&API_Response{
Errors: []string{
"Invalid Body",
},
},
"", "\t",
)
w.Write(bs)
w.Write([]byte("\n"))
return
}
// unmarshal
err = json.Unmarshal(body, request)
if err != nil ||
!request.IsValid() {
w.WriteHeader(400)
bs, _ := json.MarshalIndent(
&API_Response{
Errors: []string{
"Invalid Request",
},
},
"", "\t",
)
w.Write(bs)
w.Write([]byte("\n"))
return
}
}
response := self.api(api_endpoint_http, request)
if len(response.Errors) > 0 {
w.WriteHeader(400)
} else {
w.WriteHeader(200)
}
bs, _ := json.MarshalIndent(response, "", "\t")
w.Write(bs)
w.Write([]byte("\n"))
}