-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
270 lines (215 loc) · 6.18 KB
/
handlers.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"errors"
"fmt"
"strconv"
"github.com/fatih/color"
"github.com/gorilla/mux"
//color "github.com/fatih/color"
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
// DeviceControlHandler handles incomming control commands from client
func DeviceControlHandler(w http.ResponseWriter, r *http.Request) {
var command GenericCommand
// Read data from client
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
// Check for error
err = r.Body.Close()
if err != nil {
panic(err)
}
// Parse data from client
err = json.Unmarshal(body, &command)
fmt.Println("Calling DeviceControlHandler")
fmt.Println(command)
DispatchDeviceCommand(&command)
}
// DeviceCreateHandler handles new device request.
func DeviceCreateHandler(w http.ResponseWriter, r *http.Request) {
var device Device
// Read data from client
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
// Check for error
err = r.Body.Close()
if err != nil {
panic(err)
}
// Parse data from client
err = json.Unmarshal(body, &device)
// Check if all requered fields are filled.
if device.Name == "" || device.Type == "" {
fmt.Print("Invalid data from client. Name and Type must be defined for a new device.")
err = errors.New("Some requered field in device struct are empty.")
}
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
return
}
fmt.Println("Data fromn client:", device)
// Send response to client if new item was created
_, err = device.SaveToDB()
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(405)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
}
// DeviceDeleteHandler handles deletion of devices.
func DeviceDeleteHandler(w http.ResponseWriter, r *http.Request) {
var device Device
// Read data from client
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
// Check for error
err = r.Body.Close()
if err != nil {
panic(err)
}
// Parse data from client
err = json.Unmarshal(body, &device)
fmt.Print(device)
// Check if all requered fields are filled.
if device.ID == 0 {
fmt.Print("Invalid data from client. ID is requered when removing a device.")
err = errors.New("Some requered field in device struct are empty.")
}
if err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
return
}
fmt.Println("Data fromn client:", device)
err = device.RemoveFromDB()
if err != nil {
color.Red("Could not remove device")
}
}
// DeviceListHandler returns a list of all devices as a JSON array.
func DeviceListHandler(w http.ResponseWriter, r *http.Request) {
devices := ListDevices()
// Try to send list of devices to client
data, err := json.Marshal(struct {
Data []Device `json:"data"`
}{devices})
// If this fails responde with error code 500 for internal server error
if err != nil {
if Debug {
fmt.Println("Error: Could not connvert devices slice into JSON")
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// Internal server error
w.WriteHeader(500)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
// Respose to Request
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(200)
w.Write(data)
//fmt.Println(string(data))
}
// DeviceGetHandler handles request for data on a device with given id, returns data as JSON.
func DeviceGetHandler(w http.ResponseWriter, r *http.Request) {
//fmt.Println("Device id:", mux.Vars(r)["deviceID"])
// Get required id.
id, err := strconv.Atoi(mux.Vars(r)["deviceID"])
// Handle if id was not parsed.
if err != nil {
fmt.Println("Could not parse the given device ID")
return
}
device, err := GetDevice(id)
// Try to send list of devices to client
data, err := json.Marshal(device)
// If this fails responde with error code 500 for internal server error
if err != nil {
if Debug {
fmt.Println("Error: Could not connvert devices slice into JSON")
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// Internal server error
w.WriteHeader(500)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
// Respose to Request
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(200)
w.Write(data)
if Debug {
fmt.Println(string(data))
}
}
// RoomCreateHandler handles creation of a new room.
func RoomCreateHandler(w http.ResponseWriter, r *http.Request) {
var room Room
// Read data from client
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
// Check for error
if err := r.Body.Close(); err != nil {
panic(err)
}
// Parse data from client
if err := json.Unmarshal(body, &room); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
fmt.Println("Data fromn client:", room)
// Send response to client if new item was created
t := NewRoom(&room)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(t); err != nil {
panic(err)
}
}
// RoomListHandler lists all rooms as JSON data.
func RoomListHandler(w http.ResponseWriter, r *http.Request) {
rooms := ListRooms()
// Try to send list of devices to client
data, err := json.Marshal(rooms)
// If this fails responde with error code 500 for internal server error
if err != nil {
if Debug {
fmt.Println("Error: Could not connvert devices slice into JSON")
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// Internal server error
w.WriteHeader(500)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
// Respose to Request
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(200)
w.Write(data)
if Debug {
fmt.Println(string(data))
}
}