-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
393 lines (312 loc) · 11 KB
/
main.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package main
import (
"errors"
"fmt"
LOGS "go_svelte_lighthouse/logs"
"log"
"net/http"
"strconv"
"encoding/json"
"github.com/gorilla/mux"
CONFIG "go_svelte_lighthouse/config"
"go_svelte_lighthouse/rest"
REST "go_svelte_lighthouse/rest"
// import cron although we don't fire it manually
_ "go_svelte_lighthouse/cron"
)
// Website struct (holds the website)
type Website struct {
ID string `json:"id"`
Sitename string `json:"sitename"`
URL string `json:"url"`
Results []*Result `json:"website"`
}
// Results struct (array(slice) of results)
type Results struct {
Website *Website `json:"website"`
ResultItems []*Result `json:"resultitems"`
}
// Result struct (array(slice) of key value maps)
type Result struct {
ID string `json:"id"`
Datetime string `json:"datetime"`
ResultContainer *Results `json:"resultcontainer"`
Contents map[string]ResultMap `json:"contents"`
}
// ResultValue struct (map containing key value speed data)
type ResultMap struct {
ResultParent *Result `json:"resultparent"`
Key string `json:"key"`
Value string `json:"value"`
}
var environmentType = CONFIG.GetEnvByKey("ENVIRONMENT")
// POST | refetch a specific website
func fetchSingleWebsite(w http.ResponseWriter, r *http.Request) {
fmt.Println("Fetch single website")
// set headers
w.Header().Set("Content-Type", "application/json")
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
// get url param (in body)
requestedUrl := r.FormValue("url")
var status = false
var statusErr error
var duration int64
// fetch website report
if len(requestedUrl) > 0 {
statusMap := REST.GetWebsiteStatistics(requestedUrl)
duration = statusMap[requestedUrl].GetDuration().Milliseconds()
if !statusMap[requestedUrl].ErrorStatus() {
status = true
} else {
statusErr = statusMap[requestedUrl].GetError()
}
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "Success", "time_to_generate": strconv.FormatInt(duration, 10) + "ms"})
}
}
// POST | refetch all tracked websites
func fetchAllWebsites(w http.ResponseWriter, r *http.Request) {
// set headers
w.Header().Set("Content-Type", "application/json")
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
var status = false
var statusErr error
// fetch website report
var statusMapsCollection = REST.GetAllWebsiteStatistics(func() {})
if len(statusMapsCollection) < 1 {
statusErr = errors.New("failed to refetch any websites")
} else {
status = true
}
// get meta map from collection
var metaMap rest.FetchStatus
var timeToGenerate int64
for m := 0; m < len(statusMapsCollection); m++ {
if val, ok := statusMapsCollection[m]["meta"]; ok {
metaMap = val
timeToGenerate = metaMap.GetDuration().Milliseconds()
}
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{
"status": "Success",
"number_of_reports_generated": strconv.Itoa(len(statusMapsCollection) - 1), // minus 1 because we need to account for the extra 'timeStatusMap' meta entry
"time_to_generate": strconv.FormatInt(timeToGenerate, 10) + "ms",
})
}
}
// DELETE | delete all records for specific website
func deleteSingleWebsite(w http.ResponseWriter, r *http.Request) {
// get site_id param (in body)
var inwardID = r.FormValue("site_id")
// string to int
onwardID, err := strconv.ParseInt(inwardID, 10, 8)
if err != nil {
LOGS.ErrorLogger.Println(err)
}
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to deleteSingleWebsite missing valid site ID")
}
var status = false
var statusErr error
var duration int64
// delete site
statusMap := REST.DeleteWebsite(int(onwardID))
duration = statusMap["deleted"].GetDuration().Milliseconds()
if !statusMap["deleted"].ErrorStatus() {
status = true
} else {
statusErr = statusMap["deleted"].GetError()
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "Success", "time_to_delete": strconv.FormatInt(duration, 10) + "ms"})
}
}
// DELETE | delete a single specified record
func deleteSingleRecord(w http.ResponseWriter, r *http.Request) {
// get record_id param (in body)
var inwardID = r.FormValue("record_id")
// string to int
onwardID, err := strconv.ParseInt(inwardID, 10, 8)
if err != nil {
LOGS.ErrorLogger.Println(err)
}
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to deleteSingleRecord missing valid record ID")
}
var status = false
var statusErr error
var duration int64
// delete site
statusMap := REST.DeleteRecord(int(onwardID))
duration = statusMap["deleted"].GetDuration().Milliseconds()
if !statusMap["deleted"].ErrorStatus() {
status = true
} else {
statusErr = statusMap["deleted"].GetError()
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "Success", "time_to_delete": strconv.FormatInt(duration, 10) + "ms"})
}
}
// PATCH | update a single specified website
func updateSingleWebsite(w http.ResponseWriter, r *http.Request) {
// get record_id param (in body)
var inwardID = r.FormValue("site_id")
var inwardOnwardSitename = r.FormValue("sitename")
var inwardOnwardUrl = r.FormValue("url")
var inwardOnwardDescription = r.FormValue("description")
// string to int
onwardID, err := strconv.ParseInt(inwardID, 10, 8)
if err != nil {
LOGS.ErrorLogger.Println(err)
}
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to updateSingleWebsite missing valid site ID")
}
var status = false
var statusErr error
var duration int64
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to updateSingleWebsite missing valid record ID")
}
if len(inwardOnwardSitename) < 1 {
LOGS.DebugLogger.Println("Request to updateSingleWebsite missing updated/confirmed site name")
}
if len(inwardOnwardUrl) < 1 {
LOGS.DebugLogger.Println("Request to updateSingleWebsite missing updated/confirmed site url")
}
// description can be an empty string if required so no check here (tbc?)
// update site
statusMap := REST.UpdateWebsite(int(onwardID), inwardOnwardSitename, inwardOnwardUrl, inwardOnwardDescription)
duration = statusMap["updated"].GetDuration().Milliseconds()
if !statusMap["updated"].ErrorStatus() {
status = true
} else {
statusErr = statusMap["updated"].GetError()
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "Success", "time_to_update": strconv.FormatInt(duration, 10) + "ms"})
}
}
// PATCH | update a single specified record
func updateSingleRecord(w http.ResponseWriter, r *http.Request) {
// get record_id param (in body)
var inwardID = r.FormValue("record_id")
var inwardOnwardRecord = r.FormValue("record")
// string to int
onwardID, err := strconv.ParseInt(inwardID, 10, 8)
if err != nil {
LOGS.ErrorLogger.Println(err)
}
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to updateSingleRecord missing valid record ID")
}
var status = false
var statusErr error
var duration int64
if onwardID < 1 {
LOGS.DebugLogger.Println("Request to updateSingleRecord missing valid record ID")
}
if len(inwardOnwardRecord) < 1 {
LOGS.DebugLogger.Println("Request to updateSingleRecord missing new record string")
}
// update record
statusMap := REST.UpdateRecord(int(onwardID), inwardOnwardRecord)
duration = statusMap["updated"].GetDuration().Milliseconds()
if !statusMap["updated"].ErrorStatus() {
status = true
} else {
statusErr = statusMap["updated"].GetError()
}
// send a response depending on error or success
if !status {
json.NewEncoder(w).Encode(map[string]string{"status": "Error", "error": statusErr.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "Success", "time_to_update": strconv.FormatInt(duration, 10) + "ms"})
}
}
// GET | get details for specific website
func getSingleWebsite(w http.ResponseWriter, r *http.Request) {
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
// get request query
url := r.URL.Query()
// get requested site name
var urlToTarget string
urlToTarget = url.Get("url")
// return if no website passed
if len(urlToTarget) < 1 {
json.NewEncoder(w).Encode(map[string]string{"status": "something went wrong"})
}
// TODO
json.NewEncoder(w).Encode(map[string]string{"status": "TODO"})
}
// GET | get details for all tracked websites
func getAllWebsites(w http.ResponseWriter, r *http.Request) {
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
// TODO
}
// GET | view details for specific website in a browser, via html template
func viewSingleWebsite(w http.ResponseWriter, r *http.Request) {
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
// TODO
}
func main() {
fmt.Println("API up")
// Init router
r := mux.NewRouter()
// GET | root endpoint, test if API up
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if environmentType != "production" {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}).Methods("GET", "OPTIONS")
// ENDPOINTS -------------------------------------------------------------- //
// POST | refetch a specific website
r.HandleFunc("/website", fetchSingleWebsite).Methods("POST", "OPTIONS")
// POST | refetch all tracked websites
r.HandleFunc("/websites", fetchAllWebsites).Methods("POST", "OPTIONS")
// GET | get details for specific website
r.HandleFunc("/website", getSingleWebsite).Methods("GET", "OPTIONS")
// GET | get details for all tracked websites
r.HandleFunc("/websites", getAllWebsites).Methods("GET", "OPTIONS")
// GET | view details for specific website in a browser, via html template
r.HandleFunc("/website", viewSingleWebsite).Methods("GET", "OPTIONS")
// DELETE | delete site record and associated records
r.HandleFunc("/website", deleteSingleWebsite).Methods("DELETE", "OPTIONS")
// DELETE | delete specific record
r.HandleFunc("/record", deleteSingleRecord).Methods("DELETE", "OPTIONS")
// PUT | update specific site details
r.HandleFunc("/website", updateSingleWebsite).Methods("PATCH", "OPTIONS")
// PATCH | update specific record
r.HandleFunc("/record", updateSingleRecord).Methods("PATCH", "OPTIONS")
// Start server
log.Fatalln(http.ListenAndServe(":9999", r))
}