-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathmain.go
181 lines (168 loc) · 4.8 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
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
valid "github.com/asaskevich/govalidator"
"github.com/cassiobotaro/60-days-of-go/day13/cards"
"github.com/cassiobotaro/60-days-of-go/day13/database"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
// future ideas:
// - paginate results
// - tests
// controllers by package
// Ugly but for while is the solution
var db = database.NewMemoryDB()
// RenderJSON render a content as json(thinking about middleware)
func RenderJSON(w http.ResponseWriter, content interface{}, statusCode int) {
// Set Content-Type as json
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// HTTP STATUS CODE
w.WriteHeader(statusCode)
err := json.NewEncoder(w).Encode(content)
if err != nil {
log.Println(err)
}
}
func createCard(w http.ResponseWriter, r *http.Request) {
// initialize a card
card := cards.Card{}
// decode received content into struct
err := json.NewDecoder(r.Body).Decode(&card)
defer r.Body.Close()
if err != nil {
// Status 422 - Unprocessable entity
RenderJSON(w, map[string]string{"errors": err.Error()}, http.StatusUnprocessableEntity)
return
}
// if is a valid card
result, err := valid.ValidateStruct(card)
if result {
// create card
db.CreateCard(&card)
RenderJSON(w, card, http.StatusCreated)
} else {
// STATUS 401 - BAD REQUEST
RenderJSON(w, map[string]string{"errors": err.Error()}, http.StatusBadRequest)
}
}
func allCards(w http.ResponseWriter, r *http.Request) {
// list all cards
cardList := db.AllCards()
RenderJSON(w, cardList, http.StatusOK)
}
func getCard(w http.ResponseWriter, r *http.Request) {
// Get the id from path
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
RenderJSON(w, err, http.StatusInternalServerError)
return
}
// get the card by id
card, err := db.GetCard(id)
switch err {
case database.ErrCardNotFound:
RenderJSON(w, err, http.StatusNotFound)
case nil:
RenderJSON(w, card, http.StatusOK)
default:
RenderJSON(w, err, http.StatusInternalServerError)
}
}
func deleteCard(w http.ResponseWriter, r *http.Request) {
// Get the id from path
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
RenderJSON(w, err, http.StatusInternalServerError)
return
}
// try to delete the card from id
err = db.RemoveCard(id)
switch err {
case database.ErrCardNotFound:
RenderJSON(w, err, http.StatusNotFound)
case nil:
RenderJSON(w, "", http.StatusNoContent)
default:
RenderJSON(w, err, http.StatusInternalServerError)
}
}
func updateCard(w http.ResponseWriter, r *http.Request) {
// Get the id from path
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
RenderJSON(w, err, http.StatusInternalServerError)
return
}
card := cards.Card{}
err = json.NewDecoder(r.Body).Decode(&card)
defer r.Body.Close()
if err != nil {
RenderJSON(w, map[string]string{"errors": err.Error()}, http.StatusUnprocessableEntity)
return
}
result, err := valid.ValidateStruct(card)
card.ID = id
// if valid, update the docker
if result {
updated, err := db.UpdateCard(&card)
switch err {
case database.ErrCardNotFound:
RenderJSON(w, err, http.StatusNotFound)
case nil:
RenderJSON(w, updated, http.StatusOK)
default:
RenderJSON(w, err, http.StatusInternalServerError)
}
} else {
// STATUS 401 - BAD REQUEST
RenderJSON(w, map[string]string{"errors": err.Error()}, http.StatusBadRequest)
}
}
func partialUpdateCard(w http.ResponseWriter, r *http.Request) {
// Get the id from path
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
RenderJSON(w, err, http.StatusInternalServerError)
return
}
card := cards.Card{}
err = json.NewDecoder(r.Body).Decode(&card)
defer r.Body.Close()
if err != nil {
RenderJSON(w, map[string]string{"errors": err.Error()}, http.StatusUnprocessableEntity)
return
}
card.ID = id
updated, err := db.UpdateCard(&card)
switch err {
case database.ErrCardNotFound:
RenderJSON(w, err, http.StatusNotFound)
case nil:
RenderJSON(w, updated, http.StatusOK)
default:
RenderJSON(w, err, http.StatusInternalServerError)
}
}
func main() {
// router is a router group
r := mux.NewRouter()
r.HandleFunc("/cards", createCard).Methods(http.MethodPost)
r.HandleFunc("/cards", allCards).Methods(http.MethodGet)
r.HandleFunc("/cards/{id:[0-9]+}", getCard).Methods(http.MethodGet)
r.HandleFunc("/cards/{id:[0-9]+}", deleteCard).Methods(http.MethodDelete)
r.HandleFunc("/cards/{id:[0-9]+}", updateCard).Methods(http.MethodPut)
r.HandleFunc("/cards/{id:[0-9]+}", partialUpdateCard).Methods(http.MethodPatch)
n := negroni.Classic() // Includes some default middlewares
n.UseHandler(r)
baseURL := "localhost:3000"
log.Printf("Server running at: http://%s", baseURL)
log.Fatal(http.ListenAndServe(baseURL, n))
}