-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (82 loc) · 2.42 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var db *gorm.DB
type Todo struct {
ID uint `gorm:"primaryKey" json:"id"`
Title string `json:"title"`
Desc string `json:"desc"`
Done bool `gorm:"default:false" json:"done"`
}
func main() {
// Establish database connection
initDB()
router := gin.Default()
router.POST("/todos", addTodo)
router.GET("/todos", getTodos)
router.GET("/todos/:id", getOne)
router.PUT("/todos/:id", updateTodo)
router.DELETE("/todos/:id", removeTodo)
router.Run("0.0.0.0:3333")
}
func initDB() {
var err error
db, err = gorm.Open(sqlite.Open("database.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Auto migrate the schema
db.AutoMigrate(&Todo{})
}
func addTodo(c *gin.Context) {
var todo Todo
if err := c.ShouldBindJSON(&todo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := db.Create(&todo).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to add todo item to the database"})
return
}
c.JSON(http.StatusCreated, gin.H{"data": todo, "message": "Todo item added successfully"})
}
func getTodos(c *gin.Context) {
var todos []Todo
if err := db.Find(&todos).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve todo items from the database"})
return
}
c.JSON(http.StatusOK, gin.H{"data": todos, "total": len(todos)})
}
func getOne(c *gin.Context) {
var todo Todo
if err := db.First(&todo, c.Param("id")).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Todo item not found"})
return
}
c.JSON(http.StatusOK, gin.H{"data": todo})
}
func updateTodo(c *gin.Context) {
var todo Todo
if err := db.First(&todo, c.Param("id")).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Todo item not found"})
return
}
todo.Done = !todo.Done
if err := db.Save(&todo).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update todo item"})
return
}
c.JSON(http.StatusOK, gin.H{"data": todo, "message": "Todo item updated successfully"})
}
func removeTodo(c *gin.Context) {
if err := db.Delete(&Todo{}, c.Param("id")).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete todo item"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Todo item deleted successfully"})
}