-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (64 loc) · 1.66 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
package main
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
type todo struct {
ID string `json:"id"`
Item string `json:"item"`
Completed bool `json:"completed"`
}
var todos = []todo{
{ID: "1", Item: "Clean room", Completed: false},
{ID: "2", Item: "Read book", Completed: false},
{ID: "3", Item: "Record Video", Completed: false},
{ID: "4", Item: "Take a walk", Completed: false},
{ID: "5", Item: "Read some more books", Completed: false},
}
func getTodos(context *gin.Context) {
context.IndentedJSON(http.StatusOK, todos)
}
func getTodo(context *gin.Context) {
id := context.Param("id")
todo, err := getTodoById(id)
if err != nil {
context.IndentedJSON(http.StatusNotFound, gin.H{"message": "todo not found"})
return
}
context.IndentedJSON(http.StatusOK, todo)
}
func getTodoById(id string) (*todo, error) {
for i, t := range todos {
if t.ID == id {
return &todos[i], nil
}
}
return nil, errors.New("Todo not found")
}
func addTodo(context *gin.Context) {
var newTodo todo
if err := context.BindJSON(&newTodo); err != nil {
return
}
todos = append(todos, newTodo)
context.IndentedJSON(http.StatusCreated, newTodo)
}
func toggleTodoStatus(context *gin.Context) {
id := context.Param("id")
todo, err := getTodoById(id)
if err != nil {
context.IndentedJSON(http.StatusNotFound, gin.H{"message": "todo not found"})
return
}
todo.Completed = !todo.Completed
context.IndentedJSON(http.StatusOK, todo)
}
func main() {
router := gin.Default()
router.GET("/todos", getTodos)
router.GET("/todos/:id", getTodo)
router.PATCH("/todos/:id", toggleTodoStatus)
router.POST("/todos", addTodo)
router.Run(":5090")
}