发布于  更新于 

Gin 结合 Gorm 开发示例

1.前言

本文使用 Gin 和 Gorm 开发了一个增删改查的小项目。

2.安装 Gin 和 Gorm

1
2
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm

新建项目,main 函数import 他们的包

1
2
3
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"

因为项目简单,因此所有代码都放在 main 中

3.连接MySQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var DB *gorm.DB // 全局DB,方便后续扩展其他包调用

func initMySQL() (err error) {
dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
if err != nil {
return
}
return nil
}

dsn 处换成自己的 MySQL 配置信息。
高级配置:参考 https://gorm.io/zh_CN/docs/connecting_to_the_database.html

1
2
3
4
5
6
7
8
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
DefaultStringSize: 256, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
}), &gorm.Config{})

4.声明模型并绑定

1
2
3
4
5
type Todo struct {
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}

如想在数据库表中增加 CreatedAt , UpdatedAt 和 DeletedAt 字段,可在 Todo 模型中引入 gorm.Model 字段:

1
2
3
4
5
6
type Todo struct {
gorm.Model
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}

gorm.Model 定义如下:

1
2
3
4
5
6
type Model struct {
ID uint `gorm:"primary_key"`//primary_key:设置主键
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}

接下来最重要的一步,一定要绑定模型:

1
2
3
4
5
// 模型绑定
err = DB.AutoMigrate(&Todo{})
if err != nil {
return
}

后续执行绑定模型后会在你的 MySQL 数据库中生成一张 Todo 表:
todo_table.jpg
一般情况下表名会显示复数 Todos,改为单数的话要在 &gorm.Config 中指定启用单数 SingularTable 为 true:

1
2
3
4
5
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})

5.结合 Gin 完成增删改查

流程主要分为三步:

  1. 从请求中取出数据
  2. 操作数据库
  3. 返回响应

完整代码:

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
package main

import (
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"net/http"
)

var DB *gorm.DB

func initMySQL() (err error) {
dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
if err != nil {
return
}
return nil
}

type Todo struct {
ID int `json:"id"`
Title string `json:"title"`
Status bool `json:"status"`
}

func main() {
// 连接数据库
err := initMySQL()
if err != nil {
panic(err)
}
// 模型绑定
err = DB.AutoMigrate(&Todo{})
if err != nil {
return
}

r := gin.Default()

v1Group := r.Group("/v1")
{
// 添加
v1Group.POST("/todo", func(c *gin.Context) {
// 1.从请求中取出数据
var todo Todo
if err = c.ShouldBindJSON(&todo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
// 2.存入数据库
if err = DB.Create(&todo).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
} else {
// 3.返回响应
c.JSON(http.StatusOK, gin.H{"data": todo})
}

})
// 查看所有的待办事项
v1Group.GET("/todo", func(c *gin.Context) {
var todoList []Todo
if err = DB.Find(&todoList).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
} else {
c.JSON(http.StatusOK, gin.H{"data": todoList})
}
})
// 查看某个待办事项
v1Group.GET("/todo/:id", func(c *gin.Context) {
var todo Todo
if err = DB.First(&todo, c.Param("id")).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
} else {
c.JSON(http.StatusOK, gin.H{"data": todo})
}
})
// 更新某一个待办事项
v1Group.PUT("/todo/:id", func(c *gin.Context) {
id, ok := c.Params.Get("id")
if !ok {
c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
}
var todo Todo
if err = DB.Where("id = ?", id).First(&todo).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
}
c.ShouldBindJSON(&todo)
if err = DB.Save(&todo).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
} else {
c.JSON(http.StatusOK, gin.H{"data": todo})
}
})
// 删除某个待办事项
v1Group.DELETE("/todo/:id", func(c *gin.Context) {
var todo Todo
id, ok := c.Params.Get("id")
if !ok {
c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
}
if err = DB.Where("id = ?", id).Delete(&Todo{}).Error; err != nil {
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
} else {
c.JSON(http.StatusOK, gin.H{"data": todo})
}

})
}

err = r.Run(":8080")
if err != nil {
return
}
}

执行 go run main.go 项目启动在8080端口。