-
Notifications
You must be signed in to change notification settings - Fork 0
/
restapi.go
72 lines (60 loc) · 1.67 KB
/
restapi.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
package main
import (
"encoding/json"
"net/http"
)
type TodoController struct {
service *TodoService
}
func NewTodoController(service *TodoService) *TodoController {
return &TodoController{service}
}
func (c *TodoController) Create(w http.ResponseWriter, r *http.Request) {
todo, err := c.parseTodoRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if err := c.service.Create(todo); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func (c *TodoController) Update(w http.ResponseWriter, r *http.Request) {
todo, err := c.parseTodoRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if err := c.service.Update(todo); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (c *TodoController) Delete(w http.ResponseWriter, r *http.Request) {
todo, err := c.parseTodoRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if err := c.service.Delete(todo.ID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (c *TodoController) List(w http.ResponseWriter, r *http.Request) {
todos, err := c.service.List()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(todos)
}
func (c *TodoController) parseTodoRequest(r *http.Request) (Todo, error) {
var todo Todo
if err := json.NewDecoder(r.Body).Decode(&todo); err != nil {
return Todo{}, err
}
return todo, nil
}