-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
688 lines (640 loc) · 18.4 KB
/
router.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
_ "github.com/acarlson99/debatabase/docs" // docs is generated by Swag CLI, you have to import it.
"github.com/gorilla/mux"
httpSwagger "github.com/swaggo/http-swagger"
)
const (
errEmptyName = "name field empty"
errInvalidID = "invalid id"
errIDNotFound = "id not found"
errNotAllTagsExist = "not all tags exist"
)
// ErrJSON is an error message to be sent as response to request
type ErrJSON struct {
Code int `json:"code,omitempty"`
Msg string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
}
// writes `code` and JSON encoded `msg`
func writeError(msg string, code int, w http.ResponseWriter) {
w.WriteHeader(code)
s, err := json.Marshal(ErrJSON{
Code: code,
Msg: msg,
})
if err != nil {
panic(err)
}
w.Write(s)
}
// writes 400 error and message to signify an invalid ID
func writeInvalidIDError(w http.ResponseWriter) {
writeError(errInvalidID, 400, w)
}
// writes 404 error and appropriate error msg
func writeNotFoundError(w http.ResponseWriter) {
writeError(errIDNotFound, 404, w)
}
// internalError writes a 500 response to a ResponseWriter and logs an error
func internalError(logMsg string, w http.ResponseWriter, err error) {
log.Println("Error", logMsg+":", err)
code := 500
w.WriteHeader(code)
s, err := json.Marshal(ErrJSON{
Code: code,
// Msg: logMsg,
Error: err.Error(),
})
if err != nil {
panic(err)
}
w.Write(s)
}
// @Summary Search articles
// @Param tags query string false "Tag names" collectionFormat(csv)
// @Param limit query integer false "Maximum number of results"
// @Param offset query integer false "Results to skip. Does nothing unless 'limit' is specified"
// @Param lookslike query string false "Filter for matching names/descriptions"
// @Param orderby query string false "Field by which to order results" Enums(id, name, description)
// @Param reverse query boolean false "Reverse search results"
// @Produce json
// @Success 200 {array} main.DBArticle "All matching articles"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/search/article?tags=engine,train&limit=5&offset=5&lookslike=american&orderby=name [GET]
func searchArticle(w http.ResponseWriter, r *http.Request) {
parts := make(map[string]string)
for k, v := range r.URL.Query() {
parts[k] = v[0]
}
tags := parts["tags"]
limit, _ := strconv.Atoi(parts["limit"])
offset, _ := strconv.Atoi(parts["offset"])
lookslike := parts["lookslike"]
orderby := parts["orderby"]
rev := parts["reverse"] == "true"
sp := []string{}
if len(tags) > 0 {
sp = strings.Split(tags, ",")
}
articles, err := db.ArticlesWithTagsSearch(sp, lookslike, orderby, rev, limit, offset)
if err != nil {
internalError("querying tags", w, err)
return
}
resp, err := json.Marshal(articles)
if err != nil {
internalError("marshalling response", w, err)
return
}
w.Write(resp)
}
// @Summary Search articles by ID
// @Param id path integer false "Filter by ID"
// @Produce json
// @Success 200 {object} main.DBArticle "All matching articles"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Article not found"
// @Failure 500 {object} main.ErrJSON string "Internal error"
// @Router /api/search/article/{id} [GET]
func searchArticleID(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(mux.Vars(r)["id"])
if err != nil {
writeInvalidIDError(w)
return
}
articles, err := db.ArticleByID(int64(id))
if err != nil {
internalError("querying tags", w, err)
return
} else if articles == nil {
writeNotFoundError(w)
return
}
resp, err := json.Marshal(articles)
if err != nil {
internalError("marshalling response", w, err)
return
}
w.Write(resp)
}
// @Summary Search tags
// @Param tags query string false "Tag names" collectionFormat(csv)
// @Param limit query integer false "Maximum number of results"
// @Param offset query integer false "Results to skip. Does nothing unless 'limit' is specified"
// @Param lookslike query string false "Filter for matching names/descriptions"
// @Param orderby query string false "Field by which to order results" Enums(id, name, description)
// @Param reverse query boolean false "Reverse search results"
// @Produce json
// @Success 200 {array} main.DBTag "All matching tags"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/search/tag?tags=engine,train&limit=5&offset=5&lookslike=american&orderby=name [GET]
func searchTag(w http.ResponseWriter, r *http.Request) {
parts := make(map[string]string)
for k, v := range r.URL.Query() {
parts[k] = v[0]
}
tagStr := parts["tags"]
limit, _ := strconv.Atoi(parts["limit"])
offset, _ := strconv.Atoi(parts["offset"]) // NOTE: does nothing unless `limit` is specified
lookslike := parts["lookslike"]
orderby := parts["orderby"]
rev := parts["reverse"] == "true"
sp := []string{}
if len(tagStr) > 0 {
sp = strings.Split(tagStr, ",")
}
tags, err := db.TagSearch(sp, lookslike, orderby, rev, limit, offset)
if err != nil {
internalError("querying tags", w, err)
return
}
resp, err := json.Marshal(tags)
if err != nil {
internalError("marshalling response", w, err)
return
}
w.Write(resp)
}
// @Summary Search tags by ID
// @Param id path integer false "Filter by ID"
// @Produce json
// @Success 200 {object} main.DBTag "All matching tags"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Tag not found"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/search/tag/{id} [GET]
func searchTagID(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(mux.Vars(r)["id"])
if err != nil {
writeInvalidIDError(w)
return
}
tags, err := db.TagByID(int64(id))
if err != nil {
internalError("querying tags", w, err)
return
} else if tags == nil {
writeNotFoundError(w)
return
}
resp, err := json.Marshal(tags)
if err != nil {
internalError("marshalling response", w, err)
return
}
w.Write(resp)
}
func uploadCSVArticle(w http.ResponseWriter, r *http.Request) {
reader := csv.NewReader(r.Body)
for {
// name,url,description,tags
fields, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Println("Error parsing CSV:", err)
}
if len(fields) != 4 {
log.Println("BAD NUMNER OF FIELDS")
continue
}
a := UploadArticle{
Name: fields[0],
URL: fields[1],
Description: fields[2],
Tags: strings.Split(fields[3], ","),
}
_, err = db.InsertArticle(a)
if err != nil {
log.Println("Error inserting article:", err)
}
}
err := r.Body.Close()
if err != nil {
log.Println("Error closing http.Request body:", err)
}
}
func uploadCSVTag(w http.ResponseWriter, r *http.Request) {
reader := csv.NewReader(r.Body)
for {
// name,description
fields, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Println("Error parsing CSV:", err)
}
if len(fields) != 2 {
log.Println("BAD NUMNER OF FIELDS")
continue
}
t := UploadTag{
Name: fields[0],
Description: fields[1],
}
_, err = db.InsertTag(t)
if err != nil {
log.Println("Error inserting article:", err)
}
}
err := r.Body.Close()
if err != nil {
log.Println("Error closing http.Request body:", err)
}
}
// @Summary Create Article
// @Accept json
// @Param tag body main.UploadArticle true "Article data"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 422 {object} main.ErrJSON "Invalid tag(s)"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/upload/article [POST]
func uploadArticle(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
internalError("reading body", w, err)
return
}
article := UploadArticle{}
err = json.Unmarshal(body, &article)
if err != nil || len(article.Name) == 0 {
if err != nil {
log.Println("Error unmarshalling data:", err)
}
writeError(errEmptyName, 400, w)
return
}
article.Tags = filterArr(article.Tags, func(s string) bool {
return len(s) > 0
})
fmt.Printf("%+v\n", article)
err = r.Body.Close()
if err != nil {
log.Println("Error closing http.Request body:", err)
}
// check if all tags exist
if _, e := db.TagNamesExist(article.Tags...); !e {
writeError(errNotAllTagsExist, 422, w)
return
}
_, err = db.InsertArticle(article)
if err != nil {
internalError("inserting article", w, err)
return
}
}
// @Summary Create Tag
// @Accept json
// @Param tag body main.UploadTag true "Tag data"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 403 {object} main.ErrJSON "Duplicate tag"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/upload/tag [POST]
func uploadTag(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
internalError("reading body", w, err)
return
}
tag := UploadTag{}
err = json.Unmarshal(body, &tag)
if err != nil || len(tag.Name) == 0 {
writeError(errEmptyName, 400, w)
return
}
fmt.Printf("%+v\n", tag)
// check duplicates
if _, r := db.TagNameExists(tag.Name); r {
writeError("tag exists", 403, w)
log.Println("Not inserting tag. Already exists")
return
}
err = r.Body.Close()
if err != nil {
log.Println("Error closing http.Request body:", err)
}
_, err = db.InsertTag(tag)
if err != nil {
internalError("inserting article", w, err)
return
}
}
// @Summary Modify Article
// @Accept json
// @Param id path integer true "ID of article to modify"
// @Param article body main.UploadArticle true "Updated article data"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Article does not exist"
// @Failure 422 {object} main.ErrJSON "Invalid tag(s)"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/edit/article/{id} [POST]
func editArticle(w http.ResponseWriter, r *http.Request) {
article := UploadArticle{}
s, err := ioutil.ReadAll(r.Body)
if err != nil {
internalError("reading body", w, err)
return
}
r.Body.Close()
err = json.Unmarshal(s, &article)
id2, err2 := strconv.Atoi(mux.Vars(r)["id"])
id := int64(id2)
if err != nil {
// bad article data
writeError("invalid article", 400, w)
return
} else if err2 != nil {
// bad ID
writeInvalidIDError(w)
return
} else if len(article.Name) == 0 {
writeError(errEmptyName, 400, w)
return
}
// check if article exists
res, err := db.ArticleByID(id)
if err != nil {
internalError("querying DB", w, err)
return
} else if res == nil {
writeNotFoundError(w)
return
}
// check if tags exist
tagIDs, exists := db.TagNamesExist(article.Tags...)
if !exists {
writeError(errNotAllTagsExist, 422, w)
return
}
// update
err = db.UpdateArticle(id, article)
if err != nil {
internalError("updating article", w, err)
return
}
// update tags
err = db.RemoveArticleTags(id)
if err != nil {
internalError("removing tags", w, err)
return
}
err = db.InsertArticleTags(id, tagIDs)
if err != nil {
internalError("updating tags", w, err)
return
}
}
// @Summary Modify Tag
// @Accept json
// @Param id path integer true "ID of tag to modify"
// @Param tag body main.UploadTag true "Updated tag data"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Tag does not exist"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/edit/tag/{id} [POST]
func editTag(w http.ResponseWriter, r *http.Request) {
tag := UploadTag{}
s, err := ioutil.ReadAll(r.Body)
if err != nil {
internalError("reading body", w, err)
return
}
r.Body.Close()
err = json.Unmarshal(s, &tag)
id2, err2 := strconv.Atoi(mux.Vars(r)["id"])
id := int64(id2)
if err != nil {
// bad article data
writeError("invalid article", 400, w)
return
} else if err2 != nil {
// bad ID
writeInvalidIDError(w)
return
} else if len(tag.Name) == 0 {
writeError(errEmptyName, 400, w)
return
}
// check if exists
res, err := db.TagByID(id)
if err != nil {
internalError("querying DB", w, err)
return
} else if res == nil {
writeNotFoundError(w)
return
}
// update
err = db.UpdateTag(id, tag)
if err != nil {
internalError("updating tag", w, err)
return
}
}
// @Summary Delete Article
// @Accept json
// @Param id path integer true "ID of article to modify"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Tag does not exist"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/del/article/{id} [GET]
func deleteArticle(w http.ResponseWriter, r *http.Request) {
id2, err := strconv.Atoi(mux.Vars(r)["id"])
if err != nil {
writeInvalidIDError(w)
return
}
id := int64(id2)
res, err := db.ArticleByID(id)
if err != nil {
internalError("querying DB", w, err)
return
} else if res == nil {
writeNotFoundError(w)
return
}
err = db.RemoveArticle(id)
if err != nil {
internalError("querying DB", w, err)
return
}
err = db.RemoveArticleTags(id)
if err != nil {
internalError("querying DB", w, err)
return
}
}
// @Summary Delete Tag
// @Accept json
// @Param id path integer true "ID of tag to modify"
// @Success 200 "Ok"
// @Failure 400 {object} main.ErrJSON "Bad request"
// @Failure 404 {object} main.ErrJSON "Tag does not exist"
// @Failure 500 {object} main.ErrJSON "Internal error"
// @Router /api/del/tag/{id} [GET]
func deleteTag(w http.ResponseWriter, r *http.Request) {
id2, err := strconv.Atoi(mux.Vars(r)["id"])
if err != nil {
writeInvalidIDError(w)
return
}
id := int64(id2)
res, err := db.TagByID(id)
if err != nil {
internalError("querying DB", w, err)
return
} else if res == nil {
writeNotFoundError(w)
return
}
err = db.RemoveTag(id)
if err != nil {
internalError("querying DB", w, err)
return
}
err = db.RemoveTagsFromArticles(id)
if err != nil {
internalError("querying DB", w, err)
return
}
}
// // @Summary Create User
// // @Accept json
// // @Param user body main.DocUser true "User data"
// // @Success 200 "Ok"
// // @Failure 400 {object} main.ErrJSON "Bad request"
// // @Failure 403 {object} main.ErrJSON "Duplicate"
// // @Failure 500 {object} main.ErrJSON "Internal error"
// // @Router /api/user/create [POST]
// func userCreateHandler(w http.ResponseWriter, r *http.Request) {
// body, err := ioutil.ReadAll(r.Body)
// if err != nil {
// internalError("reading body", w, err)
// return
// }
// user := User{}
// err = json.Unmarshal(body, &user)
// if err != nil || len(user.Name) < UNameMinLen || len(user.Name) > UNameMaxLen || len(user.Passwd) < UPasswdMinLen || len(user.Passwd) > UNameMaxLen {
// if err != nil {
// log.Println("Error unmarshalling data:", err)
// writeError("malformed request", 400, w)
// } else {
// writeError("invalid fields", 400, w)
// }
// return
// }
// // no duplicates
// u, err := db.UserByName(user.Name)
// if u != nil {
// // user already exists
// // forbidden
// writeError("username taken", 403, w)
// return
// } else if err != nil {
// internalError("querying users", w, err)
// return
// }
// _, err = db.InsertUser(user)
// if err != nil {
// internalError("querying users", w, err)
// return
// }
// }
// // @Summary Log in as User
// // @Accept json
// // @Param user body main.DocUser true "User data"
// // @Success 200 {object} main.User "JWT token"
// // @Failure 400 {object} main.ErrJSON "Bad request"
// // @Failure 403 {object} main.ErrJSON "Invalid credentials"
// // @Failure 500 {object} main.ErrJSON "Internal error"
// // @Router /api/user/auth [POST]
// func userAuthHandler(w http.ResponseWriter, r *http.Request) {
// body, err := ioutil.ReadAll(r.Body)
// if err != nil {
// internalError("reading body", w, err)
// return
// }
// user := User{}
// err = json.Unmarshal(body, &user)
// if err != nil || len(user.Name) < UNameMinLen || len(user.Name) > UNameMaxLen || len(user.Passwd) < UPasswdMinLen || len(user.Passwd) > UNameMaxLen {
// if err != nil {
// log.Println("Error unmarshalling data:", err)
// writeError("malformed request", 400, w)
// } else {
// writeError("invalid fields", 400, w)
// }
// return
// }
// u, err := db.UserByName(user.Name)
// if err != nil {
// internalError("querying users", w, err)
// return
// } else if u == nil || user.Name != u.Name || user.Passwd != u.Passwd {
// // user doesn't exist. Cannot log in
// // forbidden
// writeError("invalid", 403, w)
// return
// }
// // TODO: create JWT token and write to connection
// resp, err := json.Marshal(*u)
// if err != nil {
// internalError("querying users", w, err)
// return
// }
// w.Write(resp)
// }
func enableCors(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
h.ServeHTTP(w, r)
})
}
// CreateRouter returns a new mux.Router with appropriately registered paths
func CreateRouter(frontendStaticFiles string) *mux.Router {
r := mux.NewRouter().StrictSlash(true)
r.Use(enableCors)
// swagger serve
r.PathPrefix("/swagger/").Handler(httpSwagger.Handler(
httpSwagger.URL("doc.json"),
httpSwagger.DocExpansion("list"),
))
// search
r.HandleFunc("/api/search/article/{id}", searchArticleID)
r.HandleFunc("/api/search/article", searchArticle)
r.HandleFunc("/api/search/tag/{id}", searchTagID)
r.HandleFunc("/api/search/tag", searchTag)
// upload
r.HandleFunc("/api/upload/article/csv", uploadCSVArticle).Methods("POST") // create new article
r.HandleFunc("/api/upload/article", uploadArticle).Methods("POST") // create new article
r.HandleFunc("/api/upload/tag/csv", uploadCSVTag).Methods("POST") // create new tag
r.HandleFunc("/api/upload/tag", uploadTag).Methods("POST") // create new tag
// edit
r.HandleFunc("/api/edit/article/{id}", editArticle).Methods("POST") // modify article by ID
r.HandleFunc("/api/edit/tag/{id}", editTag).Methods("POST") // modify tag by ID
// delete
r.HandleFunc("/api/del/article/{id}", deleteArticle)
r.HandleFunc("/api/del/tag/{id}", deleteTag)
// // user
// // TODO: add users
// r.HandleFunc("/api/user/create", userCreateHandler) // creates user
// r.HandleFunc("/api/user/auth", userAuthHandler) // sends Json Web Token to client if uname/passwd match DB
// serve
// TODO: fix serving, serve only `index.html` with valid path (/search /present etc.)
r.PathPrefix("/").Handler(http.FileServer(http.Dir(frontendStaticFiles)))
return r
}