Gin
是一个用Go语言编写的web框架。它是一个类似于martini
但拥有更好性能的API框架, 由于使用了httprouter
,速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin
。
Gin框架介绍
Go世界里最流行的Web框架,Github上有24K+
star。 基于httprouter开发的Web框架。 中文文档齐全,简单易用的轻量级框架。
Gin框架安装与使用
安装
下载并安装Gin
:
1
|
go get -u github.com/gin-gonic/gin
|
第一个Gin示例:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
r.Run()
}
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
|
<p>将上面的代码保存并编译执行,然后使用浏览器打开<code>127.0.0.1:8080/hello</code>就能看到一串JSON字符串。</p>
# RESTful API
<p>REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。</p>
<p>推荐阅读<a href="http://www.ruanyifeng.com/blog/2011/09/restful.html">阮一峰 理解RESTful架构</a></p>
<p>简单来说,REST的含义就是客户端与Web服务器之间进行交互的时候,使用HTTP协议中的4个请求方法代表不同的动作。</p>
<ul>
<li><code>GET</code>用来获取资源</li>
<li><code>POST</code>用来新建资源</li>
<li><code>PUT</code>用来更新资源</li>
<li><code>DELETE</code>用来删除资源。</li>
</ul>
<p>只要API程序遵循了REST风格,那就可以称其为RESTful API。目前在前后端分离的架构中,前后端基本都是通过RESTful API来进行交互。</p>
<p>例如,我们现在要编写一个管理书籍的系统,我们可以查询对一本书进行查询、创建、更新和删除等操作,我们在编写程序的时候就要设计客户端浏览器与我们Web服务端交互的方式和路径。按照经验我们通常会设计成如下模式:</p>
<table>
<thead>
<tr>
<th>请求方法</th>
<th>URL</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>GET</td>
<td>/book</td>
<td>查询书籍信息</td>
</tr>
<tr>
<td>POST</td>
<td>/create_book</td>
<td>创建书籍记录</td>
</tr>
<tr>
<td>POST</td>
<td>/update_book</td>
<td>更新书籍信息</td>
</tr>
<tr>
<td>POST</td>
<td>/delete_book</td>
<td>删除书籍信息</td>
</tr>
</tbody>
</table>
<p>同样的需求我们按照RESTful API设计如下:</p>
<table>
<thead>
<tr>
<th>请求方法</th>
<th>URL</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>GET</td>
<td>/book</td>
<td>查询书籍信息</td>
</tr>
<tr>
<td>POST</td>
<td>/book</td>
<td>创建书籍记录</td>
</tr>
<tr>
<td>PUT</td>
<td>/book</td>
<td>更新书籍信息</td>
</tr>
<tr>
<td>DELETE</td>
<td>/book</td>
<td>删除书籍信息</td>
</tr>
</tbody>
</table>
<p>Gin框架支持开发RESTful API的开发。</p>
```go
func main() {
r := gin.Default()
r.GET("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "GET",
})
})
r.POST("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "POST",
})
})
r.PUT("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "PUT",
})
})
r.DELETE("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "DELETE",
})
})
}
|
开发RESTful API的时候我们通常使用Postman来作为客户端的测试工具。
# Gin渲染 # HTML渲染
我们首先定义一个存放模板文件的templates
文件夹,然后在其内部按照业务分别定义一个posts
文件夹和一个users
文件夹。 posts/index.html
文件的内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<pre><code class="language-template">{{define "posts/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
|
users/index.html
文件的内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<pre><code class="language-template">{{define "users/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>users/index</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
|
Gin框架中使用LoadHTMLGlob()
或者LoadHTMLFiles()
方法进行HTML模板渲染。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates*")
r.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.html", gin.H{
"title": "posts/index",
})
})
r.GET("users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.html", gin.H{
"title": "users/index",
})
})
r.Run(":8080")
}
|
# 静态文件处理
当我们渲染的HTML文件中引用了静态文件时,我们只需要按照以下方式在渲染页面前调用gin.Static
方法即可。
1
2
3
4
5
6
7
|
func main() {
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLGlob("templates*")
...
r.Run(":8080")
}
|
# 补充文件路径处理
关于模板文件和静态文件的路径,我们需要根据公司/项目的要求进行设置。可以使用下面的函数获取当前执行程序的路径。
1
2
3
4
5
6
|
func getCurrentPath() string {
if ex, err := os.Executable(); err == nil {
return filepath.Dir(ex)
}
return "./"
}
|
# JSON渲染
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
func main() {
r := gin.Default()
r.GET("/someJSON", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})
})
r.GET("/moreJSON", func(c *gin.Context) {
var msg struct {
Name string `json:"user"`
Message string
Age int
}
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
c.JSON(http.StatusOK, msg)
})
r.Run(":8080")
}
|
# XML渲染
注意需要使用具名的结构体类型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
func main() {
r := gin.Default()
r.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"message": "Hello world!"})
})
r.GET("/moreXML", func(c *gin.Context) {
type MessageRecord struct {
Name string
Message string
Age int
}
var msg MessageRecord
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
c.XML(http.StatusOK, msg)
})
r.Run(":8080")
}
|
# YMAL渲染
1
2
3
|
r.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
})
|
# protobuf渲染
1
2
3
4
5
6
7
8
9
10
11
12
|
r.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
c.ProtoBuf(http.StatusOK, data)
})
|
# 获取参数 # 获取querystring参数
querystring
指的是URL中?
后面携带的参数,例如:/user/search?username=小王子&address=沙河
。 获取请求的querystring参数的方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
func main() {
r := gin.Default()
r.GET("/user/search", func(c *gin.Context) {
username := c.DefaultQuery("username", "小王子")
address := c.Query("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
r.Run()
}
|
# 获取form参数
请求的数据通过form表单来提交,例如向/user/search
发送一个POST请求,获取请求数据的方式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
func main() {
r := gin.Default()
r.POST("/user/search", func(c *gin.Context) {
username := c.PostForm("username")
address := c.PostForm("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
r.Run(":8080")
}
|
# 获取path参数
请求的参数通过URL路径传递,例如:/user/search/小王子/沙河
。 获取请求URL路径中的参数的方式如下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
func main() {
r := gin.Default()
r.GET("/user/search/:username/:address", func(c *gin.Context) {
username := c.Param("username")
address := c.Param("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
r.Run(":8080")
}
|
# 参数绑定
为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的content-type
识别请求数据类型并利用反射机制自动提取请求中querystring
、form表单、JSON、XML等参数到结构体中。
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
|
type Login struct {
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/loginJSON", func(c *gin.Context) {
var login Login
if err := c.ShouldBindJSON(&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()})
}
})
router.POST("/loginForm", func(c *gin.Context) {
var login Login
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()})
}
})
router.GET("/loginForm", func(c *gin.Context) {
var login Login
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()})
}
})
router.Run(":8080")
}
|
# 文件上传 # 单个文件上传
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
|
func main() {
router := gin.Default()
router.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(),
})
return
}
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s", file.Filename)
c.SaveUploadedFile(file, dst)
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("'%s' uploaded!", file.Filename),
})
})
router.Run()
}
|
# 多个文件上传
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
func main() {
router := gin.Default()
router.POST("/upload", func(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["file"]
for index, file := range files {
log.Println(file.Filename)
dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"message": fmt.Sprintf("%d files uploaded!", len(files)),
})
})
router.Run()
}
|
# Gin中间件
Gin框架允许开发者在处理请求的过程中,加入用户自己的钩子(Hook)函数。这个钩子函数就叫中间件,中间件适合处理一些公共的业务逻辑,比如登录校验、日志打印、耗时统计等。
Gin中的中间件必须是一个gin.HandlerFunc
类型。例如我们像下面的代码一样定义一个中间件。
1
2
3
4
5
6
7
8
9
10
11
12
|
func StatCost() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Set("name", "小王子")
c.Next()
cost := time.Since(start)
log.Println(cost)
}
}
|
然后注册中间件的时候,可以在全局注册。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
func main() {
r := gin.New()
r.Use(StatCost())
r.GET("/test", func(c *gin.Context) {
name := c.MustGet("name").(string)
log.Println(name)
c.JSON(http.StatusOK, gin.H{
"message": "Hello world!",
})
})
r.Run()
}
|
也可以给某个路由单独注册中间件。
1
2
3
4
5
6
7
8
|
r.GET("/test2", StatCost(), func(c *gin.Context) {
name := c.MustGet("name").(string)
log.Println(name)
c.JSON(http.StatusOK, gin.H{
"message": "Hello world!",
})
})
|
# 重定向 # HTTP重定向
HTTP 重定向很容易。 内部、外部重定向均支持。
1
2
3
|
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http:
})
|
# 路由重定向
路由重定向,使用HandleContext
:
1
2
3
4
5
6
7
8
|
r.GET("/test", func(c *gin.Context) {
c.Request.URL.Path = "/test2"
r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"hello": "world"})
})
|
# Gin路由 # 普通路由
1
2
3
|
r.GET("/index", func(c *gin.Context) {...})
r.GET("/login", func(c *gin.Context) {...})
r.POST("/login", func(c *gin.Context) {...})
|
此外,还有一个可以匹配所有请求方法的Any
方法如下:
1
|
r.Any("/test", func(c *gin.Context) {...})
|
为没有配置处理函数的路由添加处理程序。默认情况下它返回404代码。
1
2
3
|
r.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusNotFound, "views/404.html", nil)
})
|
# 路由组
我们可以将拥有共同URL前缀的路由划分为一个路由组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
func main() {
r := gin.Default()
userGroup := r.Group("/user")
{
userGroup.GET("/index", func(c *gin.Context) {...})
userGroup.GET("/login", func(c *gin.Context) {...})
userGroup.POST("/login", func(c *gin.Context) {...})
}
shopGroup := r.Group("/shop")
{
shopGroup.GET("/index", func(c *gin.Context) {...})
shopGroup.GET("/cart", func(c *gin.Context) {...})
shopGroup.POST("/checkout", func(c *gin.Context) {...})
}
r.Run()
}
|
通常我们将路由分组用在划分业务逻辑或划分API版本时。
# 路由原理
Gin框架中的路由使用的是httprouter这个库。
其基本原理就是构造一个路由地址的前缀树。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构