-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers.go
87 lines (72 loc) · 1.53 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
package main
import (
"github.com/gin-gonic/gin"
"log"
)
type TodoHandlers struct {
Client *TodoClient
}
// Add a new todo
func (h *TodoHandlers) AddTodo(c *gin.Context) {
var todo Todo
if err := c.Bind(&todo); err != nil {
c.JSON(400, "problem decoding body")
return
}
todo.Id = ""
created, err := h.Client.SaveTodo(todo)
if err != nil {
log.Print(err)
c.JSON(500, "problem decoding body")
return
}
c.JSON(201, created)
}
// Get all todos as an array
func (h *TodoHandlers) GetTodos(c *gin.Context) {
todos, err := h.Client.GetTodos()
if err != nil {
log.Print(err)
c.JSON(500, "problem decoding body")
return
}
c.JSON(200, todos)
}
// Get a specific todo by id
func (h *TodoHandlers) GetTodo(c *gin.Context) {
id := c.Params.ByName("id")
todo, err := h.Client.GetTodo(id)
if err != nil {
log.Print(err)
c.JSON(500, "problem decoding body")
return
}
c.JSON(200, todo)
}
// Add a new todo
func (h *TodoHandlers) SaveTodo(c *gin.Context) {
id := c.Params.ByName("id")
var todo Todo
if err := c.Bind(&todo); err != nil {
c.JSON(400, "problem decoding body")
return
}
todo.Id = id
saved, err := h.Client.SaveTodo(todo)
if err != nil {
log.Print(err)
c.JSON(500, "problem decoding body")
return
}
c.JSON(200, saved)
}
// Delete a todo by id
func (h *TodoHandlers) DeleteTodo(c *gin.Context) {
id := c.Params.ByName("id")
if err := h.Client.DeleteTodo(id); err != nil {
log.Print(err)
c.JSON(500, "problem decoding body")
return
}
c.Data(204, "application/json", make([]byte, 0))
}