-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathroutes.go
74 lines (69 loc) · 1.54 KB
/
routes.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func getAllBooks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
limit, err := getLimitParam(r)
skip, err := getSkipParam(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error": "invalid datatype for parameter"}`))
return
}
data := books.GetAllBooks(limit, skip)
b, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error": "error marshalling data"}`))
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
return
}
func getBooksByAuthor(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
author := mux.Vars(r)["author"]
data := books.GetBooksByAuthor(author)
b, err := json.Marshal(data)
//logic
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error": "error marshalling data"}`))
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
return
}
func getLimitParam(r *http.Request) (int, error) {
limit := 0
queryParams := r.URL.Query()
l := queryParams.Get("limit")
if l != "" {
val, err := strconv.Atoi(l)
if err != nil {
return limit, err
}
limit = val
}
return limit, nil
}
func getSkipParam(r *http.Request) (int, error) {
skip := 0
queryParams := r.URL.Query()
l := queryParams.Get("skip")
if l != "" {
val, err := strconv.Atoi(l)
if err != nil {
return skip, err
}
skip = val
}
return skip, nil
}