Gin 路由
1. 基本路由
- gin 框架采用的路由库是基于 httprouter做的
- 其基本原理就是构造一个路由地址的前缀树。
r.GET("/index", func(c *gin.Context) {...})
r.GET("/login", func(c *gin.Context) {...})
r.POST("/login", func(c *gin.Context) {...})
Any
匹配所有请求
r.Any("/test", func(c *gin.Context) {...})
//源码
// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
group.handle(http.MethodGet, relativePath, handlers)
group.handle(http.MethodPost, relativePath, handlers)
group.handle(http.MethodPut, relativePath, handlers)
group.handle(http.MethodPatch, relativePath, handlers)
group.handle(http.MethodHead, relativePath, handlers)
group.handle(http.MethodOptions, relativePath, handlers)
group.handle(http.MethodDelete, relativePath, handlers)
group.handle(http.MethodConnect, relativePath, handlers)
group.handle(http.MethodTrace, relativePath, handlers)
return group.returnObj()
}
为不匹配的路由设置处理函数,默认情况下它返回404代码
r.NoRoute(func(ctx *gin.Context) {...})
// 源码
// NoRoute adds handlers for NoRoute. It return a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.noRoute = handlers
engine.rebuild404Handlers()
}
2.路由组
为了管理具有相同前缀的URL, 将拥有URL共同前缀的路由划分为一组
为了代码的阅读性,使用{}包裹相同组的路由不用{}包裹并不影响效果
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
/**
路由组:
将拥有URL共同前缀的路由划分为一组, 为了代码的阅读性,使用{}包裹相同组的路由不用{}包裹并不影响效果
*/
func main() {
// 创建路由
r := gin.Default()
// 绑定路由规则
userGroup := r.Group("/user")
{
// /user/home
userGroup.GET("/home", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "/user/home")
})
// /user/login
userGroup.GET("/login", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "/user/login")
})
}
// 绑定路由规则
shopGroup := r.Group("/shop")
{
// /shop/info
shopGroup.GET("/info", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "/shop/info")
})
// /shop/cart
shopGroup.GET("/cart", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "/shop/cart")
})
}
// 监听端口
r.Run(":9000")
}
3. 路由组嵌套
// 绑定路由规则
shopGroup := r.Group("/shop")
{
// shop/book
shopBookGroup := shopGroup.Group("/book")
// shop/book/info
shopBookGroup.GET("/info", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "shop/book/info")
})
}