-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
112 lines (96 loc) · 2.56 KB
/
handlers.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
package go_ws
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jerome-laforge/go_ws/dao"
"github.com/jerome-laforge/go_ws/dao/mysql"
"github.com/jerome-laforge/go_ws/dto"
"io"
"io/ioutil"
"net/http"
"strconv"
)
var Dao dao.Repo = mysql.Repo
func Index(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Welcome!\n")
}
func TodoIndex(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(Dao.RepoGetTodos()); err != nil {
panic(err)
}
}
func TodoShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var todoId int
var err error
if todoId, err = strconv.Atoi(vars["todoId"]); err != nil {
panic(err)
}
if todo, ok := Dao.RepoFindTodo(todoId); ok {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(todo); err != nil {
panic(err)
}
return
}
// If we didn't find it, 404
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
panic(err)
}
}
/*
Test with this curl command:
curl -H "Content-Type: application/json" -d '{"name":"My first todo"}' http://localhost:8080/todos
*/
func TodoCreate(w http.ResponseWriter, r *http.Request) {
var todo dto.Todo
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
if err := json.Unmarshal(body, &todo); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
t := Dao.RepoCreateTodo(todo)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(t); err != nil {
panic(err)
}
}
/*
Test with this curl command:
curl -H "Content-Type: application/json" -X DELETE http://localhost:8080/todos/2
*/
func TodoDelete(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if vars != nil {
if sTodoId, ok := vars["todoId"]; ok {
var todo dto.Todo
todoId, err := strconv.Atoi(sTodoId)
if err == nil {
todo, err = Dao.RepoDestroyTodo(todoId)
}
if err != nil {
panic(err)
} else {
if err = json.NewEncoder(w).Encode(todo); err != nil {
panic(err)
}
}
}
}
}