-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (67 loc) · 1.7 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
package main
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
type todo struct {
ID string `json:"id"`
Item string `json: "title"`
Completed bool `json:"completed"`
}
func main() {
router := gin.Default()
router.GET("/", homepage)
router.GET("/todos", getTodos)
router.POST("/todos", addTodo)
router.GET("/todos/:id", getTodos)
router.PATCH("/todos/:id", toggleTodoStatus)
router.Run(":3000")
}
var todos = []todo{
{ID:"1", Item: "Wash the dishes", Completed: true},
{ID:"2", Item: "Clean the room", Completed: false},
{ID:"3", Item: "Apply for admission", Completed: true},
}
func homepage(context *gin.Context){
context.JSON(http.StatusOK, gin.H{"Topic": "Todo List API"})
}
func getTodos(context *gin.Context ){
context.IndentedJSON(http.StatusOK, todos)
}
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 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 getTodo(context *gin.Context) {
id := context.Param("id")
todo, err := getTodoById(id)
// check error
if err != nil {
context.IndentedJSON(http.StatusNotFound, gin.H{"message":"Todo not found"})
return
}
context.IndentedJSON(http.StatusOK, todo)
}
func toggleTodoStatus(context *gin.Context){
id := context.Param("id")
todo, err := getTodoById(id)
if err != nil {
context.IndentedJSON(http.StatusNotFound, gin.H{"message":"Todo is not found"})
return
}
todo.Completed = !todo.Completed
context.IndentedJSON(http.StatusOK, todo)
}