Gin框架学习记录 - 路由的简单使用
hanpy

Gin框架的路由是基于httprouter,httprouter使用[基数树(也叫基数特里树或压缩前缀树)]这种数据结构来维护映射路由关系,通过前缀树快速路由.

基本路由示例

http中的请求方法都有对应的方法来生成路由

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

import "github.com/gin-gonic/gin"

func main() {
// 创建一个默认的路由引擎
engine := gin.Default()
RouteBasicUse(engine)
_ = engine.Run(":9090")
}

//
// RouteBasicUse
// @Description: 路由测试
// @param r
//
func RouteBasicUse(r *gin.Engine) {
r.GET("/get", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "GET"})
})
r.POST("/post", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "POST"})
})
r.PUT("/put", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "PUT"})
})
r.DELETE("/delete", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "DELETE"})
})
r.HEAD("/head", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "HEAD"})
})
}

访问一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#1 GET
$ curl localhost:9090/get
{"method":"GET"}

#2 POST
$ curl -X POST localhost:9090/post
{"method":"POST"}

#3 PUT
$ curl -X PUT localhost:9090/put
{"method":"PUT"}

#4 DELETE
$ curl -X DELETE localhost:9090/delete
{"method":"DELETE"}

匹配所有的HTTP请求方式

Any 方法可以匹配所有的

1
2
3
engine.Any("/any", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "Any"})
})

路由组

Routes Group是为了管理一些相同的URL,直接看下面的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func RouteGroup() {
r := gin.Default()
userRoute := r.Group("/user")
{
userRoute.GET("/info", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "/user/info"})
})
userRoute.POST("/setUser", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "/user/setUser"})
})

// 分组也是可以嵌套的
setGroup := userRoute.Group("/setting")
{
setGroup.GET("/secure", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"method": "/user/setting/secure"})
})
}
}
_ = r.Run(":9090")
}

会注册下面的路由

1
2
3
[GIN-debug] GET    /user/info                --> main.RouteGroup.func1 (3 handlers)
[GIN-debug] POST /user/setUser --> main.RouteGroup.func2 (3 handlers)
[GIN-debug] GET /user/setting/secure --> main.RouteGroup.func3 (3 handlers)