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
| package routesimport (
"github.com/gin-gonic/gin"
"todo-api/models"
)type TodoRoutes struct {
DB *pgx.Conn
}func (tr *TodoRoutes) CreateTodo(c *gin.Context) {
var todo models.Todo
if err := c.ShouldBindJSON(&todo); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}_, err := tr.DB.Exec(context.Background(), "INSERT INTO todos (title) VALUES ($1)", todo.Title)
if err != nil {
c.JSON(500, gin.H{"error": "数据库操作失败"})
return
}
c.JSON(201, gin.H{"message": "成功创建任务"})
_, err := tr.DB.Exec(context.Background(), "INSERT INTO todos (title) VALUES ($1)", todo.Title)
if err != nil {
c.JSON(500, gin.H{"error": "数据库操作失败"})
return
}
c.JSON(201, gin.H{"message": "成功创建任务"})
}func (tr *TodoRoutes) GetAllTodos(c *gin.Context) {
rows, err := tr.DB.Query(context.Background(), "SELECT id, title FROM todos")
if err != nil {
c.JSON(500, gin.H{"error": "查询失败"})
return
}var todos []models.Todo
for rows.Next() {
var t models.Todo
if err := rows.Scan(&t.ID, &t.Title); err != nil {
c.JSON(500, gin.H{"error": "解析结果失败"})
return
}
todos = append(todos, t)
}
c.JSON(200, todos)
var todos []models.Todo
for rows.Next() {
var t models.Todo
if err := rows.Scan(&t.ID, &t.Title); err != nil {
c.JSON(500, gin.H{"error": "解析结果失败"})
return
}
todos = append(todos, t)
}
c.JSON(200, todos)
}
|