-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
73 lines (60 loc) 路 1.91 KB
/
handler.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
package todo
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/ifreddyrondon/bastion"
"github.com/ifreddyrondon/bastion/render"
)
// Routes creates a REST router for the todos resource
func Routes() http.Handler {
r := bastion.NewRouter()
r.Get("/", list) // GET /todos - read a list of todos
r.Post("/", create) // POST /todos - create a new todo and persist it
r.Route("/{id}", func(r chi.Router) {
r.Get("/", get) // GET /todos/{id} - read a single todo by :id
r.Put("/", update) // PUT /todos/{id} - update a single todo by :id
r.Delete("/", delete) // DELETE /todos/{id} - delete a single todo by :id
})
r.Get("/error500", error500) // GET /panic - testing 500 error
return r
}
func list(w http.ResponseWriter, r *http.Request) {
todo1 := todo{Description: "do something 1"}
todo2 := todo{Description: "do something 2"}
render.JSON.Send(w, []todo{todo1, todo2})
}
func create(w http.ResponseWriter, r *http.Request) {
var todo1 todo
if err := json.NewDecoder(r.Body).Decode(&todo1); err != nil {
panic(err) // the error should be handle
}
render.JSON.Created(w, todo1)
}
func get(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
i, _ := strconv.Atoi(id) // the error should be handle
todo1 := todo{ID: i, Description: fmt.Sprintf("do something %v", id)}
render.JSON.Send(w, todo1)
}
func update(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
i, _ := strconv.Atoi(id) // the error should be handle
var todo1 todo
if err := json.NewDecoder(r.Body).Decode(&todo1); err != nil {
panic(err) // the error should be handle
}
todo1.ID = i
render.JSON.Send(w, todo1)
}
func delete(w http.ResponseWriter, r *http.Request) {
// handle delete logic
render.JSON.NoContent(w)
}
func error500(w http.ResponseWriter, r *http.Request) {
err := errors.New("test")
render.JSON.InternalServerError(w, err)
}