Gin
安装
安装 Gin 框架
1
go get -u github.com/gin-gonic/gin
安装 fresh 插件
1
go install github.com/pilu/fresh@latest
RESTful API
GET
用来获取资源POST
用来新建资源PUT
用来更新资源DELETE
用来删除资源
获取参数
获取GET请求数据
带参数的路由: 路径中直接加上参数值
比如, 127.0.0.1:8080/user/yuan
- 使用占位符 “ : “, 必须得指定这个路径
路由: r.GET(“/user/:name”)
获取方式: c.Param(“name”)
结果: yuan
- 使用占位符 “ * “, 可以不用匹配这个路径
路由: r.GET(“/user/*name”)
获取方式: c.Param(“name”)
结果: /yuan
带参数的路由: 路径中使用参数名
路由: r.GET(“/user”)
- contxt.Query
- 传参: 127.0.0.1:8080/user/?name=yuan
- 获取: contxt.Query(“name”)
- contxt.DefaultQuery
- 传参: 127.0.0.1:8080/user/?name=yuan
- 获取: contxt.DefaultQuery(“name”,“defalutValue”)
- DefaultQuery 比 Query 多了个默认值,如果没有获取到会使用默认值
- contxt.QueryArray
- 传参: 127.0.0.1:8080/user?name=1,2,3,4,5
- 获取: names := contxt.QueryArray(“name”)
- 数据结构: [1,2,3,4,5]
- contxt.QueryMap
- 传参: 127.0.0.1:8080/user?name[1]=yuan&name[2]=jing
获取: name_map := contxt.QueryMap(“name”)
数据结构: map[1: “yuan”, 2: “jing”]
获取POST请求数据
获取表单提交的数据
c.PostForm(“key”) 获取表单中的 key 属性对应的值
前端部分代码, submit 提交
1
2
3
4
5<form action="/user" method="post">
<input type="text" name="username"><br>
<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
后端部分代码
1
2
3
4
5
6{
name := c.PostForm("username")
age := c.PostForm("age")
}
// c.DefaultPostForm(“key”, “defaultValue”) 如果没有获取到则使用指定的默认值
c.PostFormArray(“key”) 如果提交的数据有多个相同的 key,获取数组
前端部分代码, submit 提交
1
2
3
4
5
6
7
8<form action="/user" method="post">
<input type="text" name="username"><br>
<input type="text" name="age"><br>
ck1:<input type="checkbox" name="ck" value="1">
ck2:<input type="checkbox" name="ck" value="2">
ck3:<input type="checkbox" name="ck" value="3">
<input type="submit" value="提交">
</form>
后端部分代码
1
2
3
4
5
6
7
8{
r.POST("/user", func(c *gin.Context) {
arr := c.PostFormArray("ck")
c.JSON(200, gin.H{
"data": arr,
})
})
}
contxt.PostFormMap(“username”)
前端部分代码, submit提交
1
2
3
4
5<form action="/user" method="post">
<input type="text" name="username[1]"><br>
<input type="text" name="username[2]"><br>
<input type="submit" value="提交">
</form>
后端部分代码
1
2
3
4
5
6
7
8{
r.POST("/user", func(c *gin.Context) {
arr := c.PostFormMap("ck")
c.JSON(200, gin.H{
"data": arr,
})
})
}
获取querystring参数
querystring
指的是 URL 中?
后面携带的参数,例如:/user/search?name=Jack&age=18
。 获取请求的 querystring 参数的方法如下1
2
3
4
5
6
7
8
9r.GET("/search", func(c *gin.Context) {
name := c.Query("name")
age := c.Query("age")
fmt.Println(name, age) // Jack 18
c.JSON(http.StatusOK, gin.H{
"姓名": name,
"年龄": age,
})
})
获取form参数
当前端请求的数据通过 form 表单提交时,例如向
/search
发送一个POST请求,获取请求数据的方式如下1
2
3
4
5
6
7
8
9r.POST("/search", func(c *gin.Context) {
name := c.PostForm("name")
age := c.PostForm("age")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"name": name,
"age": age,
})
})
获取path参数
请求的参数通过URL路径传递,例如:
/user/Jack/Chengdu
。 获取请求URL路径中的参数的方式如下1
2
3
4
5
6
7
8
9r.GET("/user/:name/:address", func(c *gin.Context) {
name := c.Param("name")
address := c.Param("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"name": name,
"address": address,
})
})
参数绑定
为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的
Content-Type
识别请求数据类型并利用反射机制自动提取请求中QueryString
、form表单
、JSON
、XML
等参数到结构体中。 下面的示例代码演示了.ShouldBind()
强大的功能,它能够基于请求自动提取JSON
、form表单
和QueryString
类型的数据,并把值绑定到指定的结构体对象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
62package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
User string `form:"name" json:"user" binding:"required"`
Password string `form:"pwd" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// 绑定JSON的示例 ({"user": "q1mi", "password": "123456"})
router.POST("/loginJSON", func(c *gin.Context) {
var login Login
if err := c.ShouldBind(&login); err == nil {
fmt.Printf("login info:%#v\n", login)
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// 绑定form表单示例 (user=q1mi&password=123456)
router.POST("/loginForm", func(c *gin.Context) {
var login Login
// ShouldBind()会根据请求的Content-Type自行选择绑定器
if err := c.ShouldBind(&login); err == nil {
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// 绑定QueryString示例 (/loginQuery?user=q1mi&password=123456)
router.GET("/loginForm", func(c *gin.Context) {
var login Login
// ShouldBind()会根据请求的Content-Type自行选择绑定器
if err := c.ShouldBind(&login); err == nil {
c.JSON(http.StatusOK, gin.H{
"user": login.User,
"password": login.Password,
})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// Listen and serve on 0.0.0.0:8080
router.Run(":9090")
}
还有 ShouldBindWith 和ShouldBindQuery 两种绑定方式, 前者是显示绑定,
c.ShouldBindWith(&form, binding.Form)
, 后者只绑定 url 查询参数而忽略 POST 数据
上传文件
前端页面
1
2
3
4
5
6
7
8
9
10
11
12
<html lang="zh-CN">
<head>
<title>上传文件示例</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>后端
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
31package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("./index.html")
r.GET("/upload", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
r.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
c.SaveUploadedFile(file, "./source/"+file.Filename)
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("'%s' uploaded!", file.Filename),
})
})
r.Run(":9090")
}
路由重定向
外部重定向
1
2
3r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.sogo.com/")
})内部重定向
1
2
3
4
5
6
7
8r.GET("/test", func(c *gin.Context) {
// 指定重定向的URL
c.Request.URL.Path = "/test2"
r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"hello": "world"})
})
路由
any
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
29r.Any("/any", func(c *gin.Context) {
switch c.Request.Method {
case "GET":
{
c.JSON(http.StatusOK, gin.H{
"msg": "get",
})
}
case "POST":
{
c.JSON(http.StatusOK, gin.H{
"msg": "post",
})
}
case "PUT":
{
c.JSON(http.StatusOK, gin.H{
"msg": "put",
})
}
case "DELETE":
{
c.JSON(http.StatusOK, gin.H{
"msg": "delete",
})
}
}
})为没有配置处理函数的路由添加处理程序,默认情况下它返回404代码,下面的代码为没有匹配到路由的请求都返回
views/404.html
页面1
2
3
4r.LoadHTMLFiles("./404.html")
r.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusNotFound, "404.html", nil)
}
路由分组
我们可以将拥有共同 URL 前缀的路由划分为一个路由组。习惯性一对
{}
包裹同组的路由,这只是为了看着清晰,用不用{}
包裹功能上没什么区别1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23bookGroup := r.Group("/book")
{
bookGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "index",
})
})
bookGroup.POST("/new", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "new",
})
})
bookGroup.PUT("/upload", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "upload",
})
})
bookGroup.DELETE("/delete", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "delete",
})
})
}
中间件
Gin框架允许开发者在处理请求的过程中,加入用户自己的钩子(Hook)函数。这个钩子函数就叫中间件,中间件适合处理一些公共的业务逻辑,比如登录认证、权限校验、数据分页、记录日志、耗时统计等
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
47package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
)
func StatCost() gin.HandlerFunc {
return func(c *gin.Context) {
log.Println("index")
start := time.Now()
c.Set("name", "Jack") // 可以通过c.Set在请求上下文中设置值,后续的处理函数能够取到该值
// 调用该请求的剩余处理程序
c.Next()
// 不调用该请求的剩余处理程序
// c.Abort()
// 计算耗时
cost := time.Since(start)
log.Println("time: ", cost)
}
}
func m1(c *gin.Context) {
fmt.Println("m1 in...")
c.Next()
fmt.Println("m1 out...")
}
func m2(c *gin.Context) {
fmt.Println("m2 in...")
c.Next()
fmt.Println("m2 out...")
}
func main() {
r := gin.Default()
r.Use(m1, m2)
r.GET("/index", StatCost(), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "get",
})
})
r.Run(":9090")
}gin中间件中使用goroutine
当在中间件或
handler
中启动新的goroutine
时,不能使用原始的上下文(c *gin.Context),必须使用其只读副本(c.Copy()
)
Gin操控Gorm
安装
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
示例
连接数据库, 自动迁移, 增删改查
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
93package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"math/rand"
"time"
)
type UserInfo struct {
Id uint
Name string
Gender string
Hobby string
}
func main() {
// 连接数据库
db, err := gorm.Open("mysql", "user:password@(ip:port)/database?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
// // 创建表 自动迁移(把结构体和数据表进行对应)
// // gorm会根据结构体的名称来建表(如果表不存在的话)
// // 建表规则, 表名为结构体的名称的复数, 如果结构体名为复合词, 则将复合词拆开为单个词, 并以"_"连接, 最后一个单词改为复数
// db.SingularTable(true) // 禁用表名复数形式
db.AutoMigrate(&UserInfo{}) // 对应的表名 user_infos, 表名均为小写
// 创建数据行
rand.Seed(time.Now().UnixNano())
dict := [...]string{"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", "何", "吕",
"施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "任",
"袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时",
"傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "姚", "邵", "湛", "戴", "谈", "宋", "茅", "庞",
"熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭", "梅",
"盛", "林", "刁", "钟", "徐", "邱", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍"}
hobbies := []string{"游泳", "跑步", "篮球", "足球", "跳舞", "乒乓球", "羽毛球", "网球"}
fmt.Println(len(dict))
for i := 1; i <= 30; i++ {
name := dict[rand.Int()%40] + dict[rand.Int()%40+40] + dict[rand.Int()%57+80]
gender := "男"
if rand.Int()%2 == 0 {
gender = "女"
}
user := UserInfo{
Id: uint(i),
Name: name,
Gender: gender,
Hobby: hobbies[rand.Int()%8],
}
fmt.Println(user)
db.Create(user)
}
// 查询
db.Create(UserInfo{
Id: 31,
Name: "秦乐席",
Gender: "男",
Hobby: "网球",
})
var user UserInfo
// 单个结果
db.First(&user, "name=?", "秦乐席")
fmt.Println(user)
// 多个结果
db.Create(UserInfo{
Id: 32,
Name: "吕于黄",
Gender: "男",
Hobby: "网球",
})
db.Create(UserInfo{
Id: 33,
Name: "吕于黄",
Gender: "男",
Hobby: "足球",
})
var users []UserInfo
db.Where(map[string]interface{}{"Name": "吕于黄"}).Find(&users)
fmt.Println(users)
// 更新
db.Model(&user).Update("hobby", "电竞")
db.First(&user, "name=?", "秦乐席")
fmt.Println(user)
// 删除
db.Delete(&UserInfo{}, "name=? AND hobby=?", "吕于黄", "足球")
}
gorm模型
gorm
自带的模型1
2
3
4
5
6type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
}
gorm.Model
可以直接嵌套到自定义的结构体中1
2
3
4
5
6
7
8
9
10
11
12type User struct {
gorm.Model
Name string
Age sql.NullInt64 // 零值类型
Birthday *time.Time `gorm:"column:birth"` // 指定列名
Email string `gorm:"type:varchar(120);unique_index"`
Role string `gorm:"size:255"` // 字段大小为255
MemberNumber *string `gorm:"unique;not null"` // 唯一不为空
Num int `gorm:"AUTO_INCREMENT"` // 自增
Address string `gorm:"index:addr"` // 给address字段创建名为addr的索引
IgnoreMe int `gorm:"-"` // 忽略本字段
}
自定义表名
方法一
1
db.Table("yuan").CreateTable(&User{}) // 指定表名, 注意这里有大写有小写, 但是最后在数据库里都会变成小写
方法二
1
2
3
4// TableName 自定义表名称 "yuan"
func (User) TableName() string {
return "Yuan"
}
为表名设置统一前缀
可以为每个表设置统一的前缀名
1
2
3
4// 统一前缀 "uestc_"
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string { // 为每个表名设置统一前缀
return "uestc_" + defaultTableName
}
设置默认值
通过
tag
标签来设置默认值1
2
3
4
5type User struct {
Id int64
Name string `gorm:"default: 'User'"` // 如果该项未初始化, 或者初始化之后的值为零值, 那么将该项的值设为默认值
Age int64
}
注意, 如果设置了默认值, 那么对于零值或者缺省值, 都会将其设定为默认值. 下面这段代码, 最后在数据库中插入的数据都是 “user” “12”
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
32package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int64
Name string `gorm:"default: 'User'"`
Age int64
}
func main() {
db, err := gorm.Open("mysql", "user:password@(ip:port)/database?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&User{})
user1 := User{
Name: "",
Age: 12,
}
db.Debug().Create(&user1) // Debug()会在终端显示调用的sql语句
user2 := User{
Name: "",
Age: 12,
}
db.Debug().Create(&user2)
}
假如我们只对缺省值使用默认值, 对于零值不使用默认值, 有两种方法可以实现, 一是使用指针方式将零值存入数据库, 二是使用
Scanner/Valuer
方法一
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
35package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int64
Name *string `gorm:"default: 'User'"` // 如果该项未初始化, 或者初始化之后的值为零值, 那么将该项的值设为默认值
Age int64
}
func main() {
db, err := gorm.Open("mysql", "user:password@(ip:port)/database?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&User{})
user := User{
Name: new(string),
Age: 123,
}
db.Debug().Create(&user)
name := "jack"
user1 := User{
Name: &name,
Age: 123,
}
db.Debug().Create(&user1)
}
结果如图:
方法二
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
58package main
import (
"database/sql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Id int64
Name sql.NullString `gorm:"default: 'User'"` // 如果该项未初始化, 或者初始化之后的值为零值, 那么将该项的值设为默认值
Age int64
}
func main() {
db, err := gorm.Open("mysql", "user:password@(ip:port)/database?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.AutoMigrate(&User{})
user := User{
Name: sql.NullString{
String: "",
Valid: true, // Valid为true代表String是有初始值, 不需要用默认值填充Name, 使用String来填充Name
},
Age: 18,
}
db.Debug().Create(&user)
user1 := User{
Name: sql.NullString{
String: "",
Valid: false, // Valid为false代表String是零值或空值, 需要用默认值填充Name
},
Age: 12,
}
db.Debug().Create(&user1)
user2 := User{
Name: sql.NullString{
String: "Any",
Valid: false, // 如果String有值, 但是Valid设为false, 那么会使用Null来填充Name
},
Age: 12,
}
db.Debug().Create(&user2)
user3 := User{
Name: sql.NullString{
String: "Any",
Valid: true, // // 如果String有值, 且Valid为true, 那么不需要用默认值填充Name, 使用String来填充Name
},
Age: 12,
}
db.Debug().Create(&user3)
}
结果如图:
查询
一般查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// 根据主键查询第一条记录
db.First(&user)
//// SELECT * FROM users ORDER BY id LIMIT 1;
// 随机获取一条记录
db.Take(&user)
//// SELECT * FROM users LIMIT 1;
// 根据主键查询最后一条记录
db.Last(&user)
//// SELECT * FROM users ORDER BY id DESC LIMIT 1;
// 查询所有的记录
db.Find(&users)
//// SELECT * FROM users;
// 查询指定的某条记录(仅当主键为整型时可用)
db.First(&user, 10)
//// SELECT * FROM users WHERE id = 10;
where
查询普通
sql
查询.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// Get first matched record
db.Where("name = ?", "Yuan").First(&user)
//// SELECT * FROM users WHERE name = 'Yuan' limit 1;
// Get all matched records
db.Where("name = ?", "Yuan").Find(&users)
//// SELECT * FROM users WHERE name = 'Yuan';
// <>
db.Where("name <> ?", "Yuan").Find(&users)
//// SELECT * FROM users WHERE name <> 'Yuan';
// IN
db.Where("name IN (?)", []string{"Yuan", "Jing"}).Find(&users)
//// SELECT * FROM users WHERE name in ('Yuan','Jing');
// LIKE
db.Where("name LIKE ?", "%jin%").Find(&users)
//// SELECT * FROM users WHERE name LIKE '%jin%';
// AND
db.Where("name = ? AND age >= ?", "Yuan", "22").Find(&users)
//// SELECT * FROM users WHERE name = 'Yuan' AND age >= 22;
// Time
db.Where("updated_at > ?", lastWeek).Find(&users)
//// SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
// BETWEEN
db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
//// SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00';
Struct & Map
查询1
2
3
4
5
6
7
8
9
10
11// Struct
db.Where(&User{Name: "Yuan", Age: 20}).First(&user)
//// SELECT * FROM users WHERE name = "Yuan" AND age = 20 LIMIT 1;
// Map
db.Where(map[string]interface{}{"name": "Yuan", "age": 20}).Find(&users)
//// SELECT * FROM users WHERE name = "Yuan" AND age = 20;
// 主键的切片
db.Where([]int64{20, 21, 22}).Find(&users)
//// SELECT * FROM users WHERE id IN (20, 21, 22);
Not
查询1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21db.Not("name", "Yuan").First(&user)
//// SELECT * FROM users WHERE name <> "Yuan" LIMIT 1;
// Not In
db.Not("name", []string{"Yuan", "Jing"}).Find(&users)
//// SELECT * FROM users WHERE name NOT IN ("Yuan", "Jing");
// Not In slice of primary keys
db.Not([]int64{1,2,3}).First(&user)
//// SELECT * FROM users WHERE id NOT IN (1,2,3);
db.Not([]int64{}).First(&user)
//// SELECT * FROM users;
// Plain SQL
db.Not("name = ?", "Yuan").First(&user)
//// SELECT * FROM users WHERE NOT(name = "Yuan");
// Struct
db.Not(User{Name: "Yuan"}).First(&user)
//// SELECT * FROM users WHERE name <> "Yuan";
Or
查询1
2
3
4
5
6
7
8
9
10db.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&users)
//// SELECT * FROM users WHERE role = 'admin' OR role = 'super_admin';
// Struct
db.Where("name = 'Yuan'").Or(User{Name: "Jing"}).Find(&users)
//// SELECT * FROM users WHERE name = 'Yuan' OR name = 'Jing';
// Map
db.Where("name = 'Yuan'").Or(map[string]interface{}{"name": "Jing"}).Find(&users)
//// SELECT * FROM users WHERE name = 'Yuan' OR name = 'Jing';
内敛条件
作用与
Where
查询类似,当内联条件与多个立即执行方法一起使用时, 内联条件不会传递给后面的立即执行方法立即执行方法是指那些会立即生成
SQL
语句并发送到数据库的方法, 他们一般是CRUD
方法,比如:Create
,First
,Find
,Take
,Save
,UpdateXXX
,Delete
,Scan
,Row
,Rows
…这有一个基于上面链式方法代码的立即执行方法的例子:
1
tx.Find(&user)
生成的SQL语句如下:
1
SELECT * FROM users where name = 'Yuan' AND age = 30 AND active = 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// 根据主键获取记录 (只适用于整形主键)
db.First(&user, 23)
//// SELECT * FROM users WHERE id = 23 LIMIT 1;
// 根据主键获取记录, 如果它是一个非整形主键
db.First(&user, "id = ?", "string_primary_key")
//// SELECT * FROM users WHERE id = 'string_primary_key' LIMIT 1;
// Plain SQL
db.Find(&user, "name = ?", "Yuan")
//// SELECT * FROM users WHERE name = "Yuan";
db.Find(&users, "name <> ? AND age > ?", "Yuan", 20)
//// SELECT * FROM users WHERE name <> "Yuan" AND age > 20;
// Struct
db.Find(&users, User{Age: 20})
//// SELECT * FROM users WHERE age = 20;
// Map
db.Find(&users, map[string]interface{}{"age": 20})
//// SELECT * FROM users WHERE age = 20;
额外查询选项
1
2
3// 为查询 SQL 添加额外的 SQL 操作
db.Set("gorm:query_option", "FOR UPDATE").First(&user, 10)
//// SELECT * FROM users WHERE id = 10 FOR UPDATE;
FirstOrInit
获取匹配的第一条记录,否则根据给定的条件初始化一个新的对象 (仅支持struct
和map
条件)1
2
3
4
5
6
7
8
9// 未找到
db.FirstOrInit(&user, User{Name: "non_existing"})
//// user -> User{Name: "non_existing"}
// 找到
db.Where(User{Name: "Yuan"}).FirstOrInit(&user)
//// user -> User{Id: 111, Name: "Yuan", Age: 20}
db.FirstOrInit(&user, map[string]interface{}{"name": "Yuan"})
//// user -> User{Id: 111, Name: "Yuan", Age: 20}
Attrs
, 如果记录未找到, 将使用参数初始化struct
1
2
3
4
5
6
7
8
9
10
11
12
13// 未找到
db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrInit(&user)
//// SELECT * FROM USERS WHERE name = 'non_existing';
//// user -> User{Name: "non_existing", Age: 20}
db.Where(User{Name: "non_existing"}).Attrs("age", 20).FirstOrInit(&user)
//// SELECT * FROM USERS WHERE name = 'non_existing';
//// user -> User{Name: "non_existing", Age: 20}
// 找到
db.Where(User{Name: "Yuan"}).Attrs(User{Age: 30}).FirstOrInit(&user)
//// SELECT * FROM USERS WHERE name = Yuan';
//// user -> User{Id: 111, Name: "Yuan", Age: 20}
Assign
, 不管记录是否找到,都将参数赋值给struct
1
2
3
4
5
6
7
8// 未找到
db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrInit(&user)
//// user -> User{Name: "non_existing", Age: 20}
// 找到
db.Where(User{Name: "Yuan"}).Assign(User{Age: 30}).FirstOrInit(&user)
//// SELECT * FROM USERS WHERE name = Yuan';
//// user -> User{Id: 111, Name: "Yuan", Age: 30}
FirstOrCreate
, 获取匹配的第一条记录, 否则根据给定的条件创建一个新的记录 (仅支持struct
和map
条件)1
2
3
4
5
6
7
8// 未找到
db.FirstOrCreate(&user, User{Name: "non_existing"})
//// INSERT INTO "users" (name) VALUES ("non_existing");
//// user -> User{Id: 112, Name: "non_existing"}
// 找到
db.Where(User{Name: "Yuan"}).FirstOrCreate(&user)
//// user -> User{Id: 111, Name: "Yuan"}
Attrs
, 如果记录未找到,将使用参数创建struct
和记录1
2
3
4
5
6
7
8
9
10// 未找到
db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user)
//// SELECT * FROM users WHERE name = 'non_existing';
//// INSERT INTO "users" (name, age) VALUES ("non_existing", 20);
//// user -> User{Id: 112, Name: "non_existing", Age: 20}
// 找到
db.Where(User{Name: "Yuan"}).Attrs(User{Age: 30}).FirstOrCreate(&user)
//// SELECT * FROM users WHERE name = 'Yuan';
//// user -> User{Id: 111, Name: "Yuan", Age: 20}
Assgin
, 不管记录是否找到,都将参数赋值给 struct 并保存至数据库1
2
3
4
5
6
7
8
9
10
11// 未找到
db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrCreate(&user)
//// SELECT * FROM users WHERE name = 'non_existing';
//// INSERT INTO "users" (name, age) VALUES ("non_existing", 20);
//// user -> User{Id: 112, Name: "non_existing", Age: 20}
// 找到
db.Where(User{Name: "Yuan"}).Assign(User{Age: 30}).FirstOrCreate(&user)
//// SELECT * FROM users WHERE name = 'Yuan';
//// UPDATE users SET age=30 WHERE id = 111;
//// user -> User{Id: 111, Name: "Yuan", Age: 30}
高级查询
选择字段
1
2
3
4
5
6
7
8db.Select("name, age").Find(&users)
//// SELECT name, age FROM users;
db.Select([]string{"name", "age"}).Find(&users)
//// SELECT name, age FROM users;
db.Table("users").Select("COALESCE(age,?)", 42).Rows()
//// SELECT COALESCE(age,'42') FROM users;
排序
1
2
3
4
5
6
7
8
9
10
11db.Order("age desc, name").Find(&users)
//// SELECT * FROM users ORDER BY age desc, name;
// 多字段排序
db.Order("age desc").Order("name").Find(&users)
//// SELECT * FROM users ORDER BY age desc, name;
// 覆盖排序
db.Order("age desc").Find(&users1).Order("age", true).Find(&users2)
//// SELECT * FROM users ORDER BY age desc; (users1)
//// SELECT * FROM users ORDER BY age; (users2)
数量
1
2
3
4
5
6
7db.Limit(3).Find(&users)
//// SELECT * FROM users LIMIT 3;
// -1 取消 Limit 条件
db.Limit(10).Find(&users1).Limit(-1).Find(&users2)
//// SELECT * FROM users LIMIT 10; (users1)
//// SELECT * FROM users; (users2)
偏移
1
2
3
4
5
6
7db.Offset(3).Find(&users)
//// SELECT * FROM users OFFSET 3;
// -1 取消 Offset 条件
db.Offset(10).Find(&users1).Offset(-1).Find(&users2)
//// SELECT * FROM users OFFSET 10; (users1)
//// SELECT * FROM users; (users2)
总数
1
2
3
4
5
6
7
8
9
10
11
12db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count)
//// SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users)
//// SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count)
db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count)
//// SELECT count(*) FROM users WHERE name = 'jinzhu'; (count)
db.Table("deleted_users").Count(&count)
//// SELECT count(*) FROM deleted_users;
db.Table("deleted_users").Select("count(distinct(name))").Count(&count)
//// SELECT count( distinct(name) ) FROM deleted_users; (count)
Group & Having
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Rows()
for rows.Next() {
...
}
// 使用Scan将多条结果扫描进事先准备好的结构体切片中
type Result struct {
Date time.Time
Total int
}
var rets []Result
db.Table("users").Select("date(created_at) as date, sum(age) as total").Group("date(created_at)").Scan(&rets)
rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Rows()
for rows.Next() {
...
}
type Result struct {
Date time.Time
Total int64
}
db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results)
连接
1
2
3
4
5
6
7
8
9rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows()
for rows.Next() {
...
}
db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results)
// 多连接及参数
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Joins("JOIN credit_cards ON credit_cards.user_id = users.id").Where("credit_cards.number = ?", "411111111111").Find(&user)
Pluck
, 查询model
中的一个列作为切片,如果您想要查询多个列,您应该使用Scan
1
2
3
4
5
6
7
8
9
10var ages []int64
db.Find(&users).Pluck("age", &ages)
var names []string
db.Model(&User{}).Pluck("name", &names)
db.Table("deleted_users").Pluck("name", &names)
// 想查询多个字段? 这样做:
db.Select("name, age").Find(&users)
扫描, 扫描结果至一个
struct
1
2
3
4
5
6
7
8
9
10
11
12
13type Result struct {
Name string
Age int
}
var result Result
db.Table("users").Select("name, age").Where("name = ?", "Antonio").Scan(&result)
var results []Result
db.Table("users").Select("name, age").Where("id > ?", 0).Scan(&results)
// 原生 SQL
db.Raw("SELECT name, age FROM users WHERE name = ?", "Antonio").Scan(&result)
链式操作
Gorm
实现了链式操作接口,所以你可以把代码写成下面这样. 在调用立即执行方法前不会生成Query
语句,借助这个特性你可以创建一个函数来处理一些通用逻辑。1
2
3
4
5
6
7
8
9
10
11
12
13// 创建一个查询
tx := db.Where("name = ?", "YuanYuan")
// 添加更多条件
if someCondition {
tx = tx.Where("age = ?", 20)
} else {
tx = tx.Where("age = ?", 30)
}
if yetAnotherCondition {
tx = tx.Where("active = ?", 1)
}
范围,
Scope
是建立在链式操作的基础之上的. 基于它,你可以抽取一些通用逻辑,写出更多可重用的函数库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
26func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
return db.Where("amount > ?", 1000)
}
func PaidWithCreditCard(db *gorm.DB) *gorm.DB {
return db.Where("pay_mode_sign = ?", "C")
}
func PaidWithCod(db *gorm.DB) *gorm.DB {
return db.Where("pay_mode_sign = ?", "C")
}
func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
return func (db *gorm.DB) *gorm.DB {
return db.Scopes(AmountGreaterThan1000).Where("status IN (?)", status)
}
}
db.Scopes(AmountGreaterThan1000, PaidWithCreditCard).Find(&orders)
// 查找所有金额大于 1000 的信用卡订单
db.Scopes(AmountGreaterThan1000, PaidWithCod).Find(&orders)
// 查找所有金额大于 1000 的 COD 订单
db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)
// 查找所有金额大于 1000 且已付款或者已发货的订单
多个立即执行方法, 在
GORM
中使用多个立即执行方法时,后一个立即执行方法会复用前一个立即执行方法的条件 (不包括内联条件) 。1
db.Where("name LIKE ?", "jinzhu%").Find(&users, "id IN (?)", []int{1, 2, 3}).Count(&count)
生成的 Sql
1
2
3SELECT * FROM users WHERE name LIKE 'jinzhu%' AND id IN (1, 2, 3)
SELECT count(*) FROM users WHERE name LIKE 'jinzhu%'
更新
更新所有字段,
Save()
默认会更新该对象的所有字段,即使你没有赋值。1
2
3
4
5
6
7db.First(&user)
user.Name = "YuanYuan"
user.Age = 99
db.Save(&user)
//// UPDATE `users` SET `created_at` = '2020-02-16 12:52:20', `updated_at` = '2020-02-16 12:54:55', `deleted_at` = NULL, `name` = '七米', `age` = 99, `active` = true WHERE `users`.`deleted_at` IS NULL AND `users`.`id` = 1
更新修改字段, 可以使用
update
或者updates
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// 更新单个属性,如果它有变化
db.Model(&user).Update("name", "hello")
//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
// 根据给定的条件更新单个属性
db.Model(&user).Where("active = ?", true).Update("name", "hello")
//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;
// 使用 map 更新多个属性,只会更新其中有变化的属性
db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
//// UPDATE users SET name='hello', age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
// 使用 struct 更新多个属性,只会更新其中有变化且为非零值的字段
db.Model(&user).Updates(User{Name: "hello", Age: 18})
//// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;
// 警告:当使用 struct 更新时,GORM只会更新那些非零值的字段
// 对于下面的操作,不会发生任何更新,"", 0, false 都是其类型的零值
db.Model(&user).Updates(User{Name: "", Age: 0, Active: false})
更新选定字段, 如果你想更新或忽略某些字段,你可以使用
Select
,Omit
1
2
3
4
5db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
db.Model(&user).Omit("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
//// UPDATE users SET age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
无
Hooks
更新, 上面的更新操作会自动运行 model 的BeforeUpdate
,AfterUpdate
方法,更新UpdatedAt
时间戳, 在更新时保存其Associations
, 如果你不想调用这些方法,你可以使用UpdateColumn
,UpdateColumns
1
2
3
4
5
6
7// 更新单个属性,类似于 `Update`
db.Model(&user).UpdateColumn("name", "hello")
//// UPDATE users SET name='hello' WHERE id = 111;
// 更新多个属性,类似于 `Updates`
db.Model(&user).UpdateColumns(User{Name: "hello", Age: 18})
//// UPDATE users SET name='hello', age=18 WHERE id = 111;
批量更新, 批量更新时,
Hooks
不会运行1
2
3
4
5
6
7
8
9db.Table("users").Where("id IN (?)", []int{10, 11}).Updates(map[string]interface{}{"name": "hello", "age": 18})
//// UPDATE users SET name='hello', age=18 WHERE id IN (10, 11);
// 使用 struct 更新时,只会更新非零值字段,若想更新所有字段,请使用map[string]interface{}
db.Model(User{}).Updates(User{Name: "hello", Age: 18})
//// UPDATE users SET name='hello', age=18;
// 使用 `RowsAffected` 获取更新记录总数
db.Model(User{}).Updates(User{Name: "hello", Age: 18}).RowsAffected
使用
SQL
表达式更新, 先查询表中的第一条数据保存至user变量1
2
3
4
5
6
7
8
9
10
11
12
13
14var user User
db.First(&user)
db.Model(&user).Update("age", gorm.Expr("age * ? + ?", 2, 100))
//// UPDATE `users` SET `age` = age * 2 + 100, `updated_at` = '2020-02-16 13:10:20' WHERE `users`.`id` = 1;
db.Model(&user).Updates(map[string]interface{}{"age": gorm.Expr("age * ? + ?", 2, 100)})
//// UPDATE "users" SET "age" = age * '2' + '100', "updated_at" = '2020-02-16 13:05:51' WHERE `users`.`id` = 1;
db.Model(&user).UpdateColumn("age", gorm.Expr("age - ?", 1))
//// UPDATE "users" SET "age" = age - 1 WHERE "id" = '1';
db.Model(&user).Where("age > 10").UpdateColumn("age", gorm.Expr("age - ?", 1))
//// UPDATE "users" SET "age" = age - 1 WHERE "id" = '1' AND quantity > 10;
其他更新选项
1
2
3// 为 update SQL 添加其它的 SQL
db.Model(&user).Set("gorm:update_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Update("name", "hello")
//// UPDATE users SET name='hello', updated_at = '2013-11-17 21:34:10' WHERE id=111 OPTION (OPTIMIZE FOR UNKNOWN);
删除
删除记录, 警告 删除记录时,请确保主键字段有值,GORM 会通过主键去删除记录,如果主键为空,GORM 会删除该 model 的所有记录。
1
2
3
4
5
6
7// 删除现有记录
db.Delete(&email)
//// DELETE from emails where id=10;
// 为删除 SQL 添加额外的 SQL 操作
db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
//// DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);
批量删除
1
2
3
4
5db.Where("email LIKE ?", "%Yuan%").Delete(Email{})
//// DELETE from emails where email LIKE "%Yuan%";
db.Delete(Email{}, "email LIKE ?", "%Yuan%")
//// DELETE from emails where email LIKE "%Yuan%";
软删除, 如果一个 model 有
DeletedAt
字段,他将自动获得软删除的功能! 当调用Delete
方法时, 记录不会真正的从数据库中被删除, 只会将DeletedAt
字段的值会被设置为当前时间1
2
3
4
5
6
7
8
9
10
11
12
13
14db.Delete(&user)
//// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
// 批量删除
db.Where("age = ?", 20).Delete(&User{})
//// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
// 查询记录时会忽略被软删除的记录
db.Where("age = 20").Find(&user)
//// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
// Unscoped 方法可以查询被软删除的记录
db.Unscoped().Where("age = 20").Find(&users)
//// SELECT * FROM users WHERE age = 20;
物理删除
1
2
3// Unscoped 方法可以物理删除记录
db.Unscoped().Delete(&order)
//// DELETE FROM orders WHERE id=10;
设置 Cookie
在 gin 中设置 cookie 时遇到不少障碍
1
2// c.SetCookie(name string, value string, maxAge int, path string, domain string, secure bool, httpOnly bool)
c.SetCookie("username", u.Name, 60, "/", "localhost", false, true)之前将
domain
字段设置为 “127.0.0.1”, 导致 cookie 一直设置不成功. 直到后面看了官方的文档, 将其设置为 “localhost” 才成功设置完 cookie 后, 在重定向阶段又出现了问题
1
2
3
4
5
6
7
8
9// 方法一
{
c.HTML(http.StatusOK, "login.html", nil)
}
// 方法二
{
c.Request.URL.Path = "/login"
r.HandleContext(c)
}方法一是返回一个 HTML 界面, 方法二是路由重定向, 这两种方法的效果就是浏览器中的路由不会发生改变
1
2
3
4
5
6
7
8
9
10// 方法三
{
r.GET("/test", func(c *gin.Context) {
if xxx {
c.Redirect(http.StatusMovedPermanently, "/login")
}else{
...
}
})
}在我的浏览器上测试, 会导致的后果就是, 一旦 if 为真, 也就是执行了第五行代码, 那么以后每次走到 /test 这个路由, 就会直接转到 /login 路由上去, 不管 if 真假都会这样, 而且浏览器中的路由也会变成 /login
1
2
3
4
5
6
7
8
9
10// 方法四
{
r.GET("/test", func(c *gin.Context) {
if xxx {
c.Redirect(http.StatusFound, "/login")
}else{
...
}
})
}这种方法就没有上面那么多的幺蛾子, 条件满足才转到相应的路由, 并且浏览器中的路由也会变成相应的路由
中间件 BasicAuth 路由组权限
代码
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
42package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
var adminUsers = gin.H{
"Yuan": gin.H{"email": "960625@qq.com", "phone": "123456"},
"Jing": gin.H{"email": "961213@qq.com", "phone": "654321"},
"Gao": gin.H{"email": "Gao@qq.com", "phone": "666666"},
"Chen": gin.H{"email": "Chen@qq.com", "phone": "333333"},
}
func MiddleA(c *gin.Context) {
user := c.MustGet(gin.AuthUserKey).(string)
secret, ok := adminUsers[user]
if ok {
c.JSON(http.StatusOK, gin.H{
"user": user,
"secret": secret,
})
} else {
c.JSON(http.StatusOK, gin.H{
"user": user,
"secret": "No secret",
})
}
}
func main() {
r := gin.Default()
routerGroup := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"Jing": "2234",
"Gao": "3234",
"Chen": "4234",
}))
routerGroup.GET("/secret", MiddleA)
r.Run()
}
结尾
- 本文作者: 谷安
- 本文链接: http://example.com/2022/11/27/gin/
- 版权声明: 转载请注明出处