-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
189 lines (146 loc) · 4.26 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type ToDoItem struct {
Id int `json:"id" gorm:"column:id;"`
Title string `json:"title" gorm:"column:title;"`
Status string `json:"status" gorm:"column:status;"`
CreatedAt *time.Time `json:"created_at" gorm:"column:created_at;"`
UpdatedAt *time.Time `json:"updated_at" gorm:"column:updated_at;"`
}
func (ToDoItem) TableName() string { return "todo_items" }
func main() {
// Checking that an environment variable is present or not.
mysqlConnStr, ok := os.LookupEnv("MYSQL_CONNECTION")
if !ok {
log.Fatalln("Missing MySQL connection string.")
}
dsn := mysqlConnStr
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalln("Cannot connect to MySQL:", err)
}
log.Println("Connected to MySQL:", db)
router := gin.Default()
v1 := router.Group("/v1")
{
v1.POST("/items", createItem(db)) // create item
v1.GET("/items", getListOfItems(db)) // list items
v1.GET("/items/:id", readItemById(db)) // get an item by ID
v1.PUT("/items/:id", editItemById(db)) // edit an item by ID
v1.DELETE("/items/:id", deleteItemById(db)) // delete an item by ID
}
router.Run()
}
func createItem(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
var dataItem ToDoItem
if err := c.ShouldBind(&dataItem); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// preprocess title - trim all spaces
dataItem.Title = strings.TrimSpace(dataItem.Title)
if dataItem.Title == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "title cannot be blank"})
return
}
// do not allow "finished" status when creating a new task
dataItem.Status = "Doing" // set to default
if err := db.Create(&dataItem).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": dataItem.Id})
}
}
func readItemById(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
var dataItem ToDoItem
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := db.Where("id = ?", id).First(&dataItem).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": dataItem})
}
}
func getListOfItems(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
type DataPaging struct {
Page int `json:"page" form:"page"`
Limit int `json:"limit" form:"limit"`
Total int64 `json:"total" form:"-"`
}
var paging DataPaging
if err := c.ShouldBind(&paging); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if paging.Page <= 0 {
paging.Page = 1
}
if paging.Limit <= 0 {
paging.Limit = 10
}
offset := (paging.Page - 1) * paging.Limit
var result []ToDoItem
if err := db.Table(ToDoItem{}.TableName()).
Count(&paging.Total).
Offset(offset).
Order("id desc").
Find(&result).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": result})
}
}
func editItemById(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var dataItem ToDoItem
if err := c.ShouldBind(&dataItem); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := db.Where("id = ?", id).Updates(&dataItem).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": true})
}
}
func deleteItemById(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := db.Table(ToDoItem{}.TableName()).
Where("id = ?", id).
Delete(nil).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": true})
}
}