Newer
Older
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
113
114
115
116
117
118
package controllers
import (
"Todo/models"
"database/sql"
"encoding/json"
"fmt"
"strconv"
"github.com/beego/beego/v2/server/web"
)
type TodoController struct {
web.Controller
model models.TodoModel
}
func NewTodoController(db *sql.DB) *TodoController {
return &TodoController{
model: models.TodoModel{DB: db},
}
}
func (this *TodoController) OutputContext(status int, message string) {
this.Ctx.Output.SetStatus(status)
this.Ctx.Output.Body([]byte(message + "\n"))
}
func (c *TodoController) Index() {
c.OutputContext(200, "Welcome to the Todo API")
}
func (this *TodoController) ListTodos() {
todos, err := this.model.All()
if err != nil {
this.OutputContext(500, "Failed to fetch todos")
return
}
this.Data["json"] = todos
this.ServeJSON()
}
func (this *TodoController) NewTodo() {
req := struct{ Name string }{}
err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
if err != nil || req.Name == "" {
this.OutputContext(400, "Invalid request: empty name")
return
}
fmt.Println(req)
_, err = this.model.Create(req.Name)
if err != nil {
this.OutputContext(500, "Failed to create todo")
return
}
this.OutputContext(201, "Todo created successfully")
}
func (this *TodoController) GetTodo() {
ids := this.Ctx.Input.Param(":id")
id, _ := strconv.Atoi(ids)
todo, err := this.model.Find(id)
if err != nil {
this.OutputContext(404, "Todo not found")
return
}
this.Data["json"] = todo
this.ServeJSON()
}
func (this *TodoController) UpdateTodo() {
ids := this.Ctx.Input.Param(":id")
id, _ := strconv.Atoi(ids)
req := struct {
Name string
Done string
}{}
err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
if err != nil {
this.OutputContext(400, "Invalid request: "+err.Error())
return
}
todo, err := this.model.Find(id)
if err != nil {
this.OutputContext(404, "Todo not found")
return
}
if req.Name != "" {
todo.Name = req.Name
}
if req.Done == "true" {
todo.Done = true
} else if req.Done == "false" {
todo.Done = false
}
err = this.model.Update(id, todo.Name, todo.Done)
if err != nil {
this.OutputContext(500, "Failed to update todo")
return
}
this.OutputContext(200, "Todo updated successfully")
}
func (this *TodoController) DeleteTodo() {
ids := this.Ctx.Input.Param(":id")
id, _ := strconv.Atoi(ids)
err := this.model.Delete(id)
if err != nil {
this.OutputContext(500, "Failed to delete todo")
return
}
this.OutputContext(200, "Todo deleted successfully")
}