[Gin] 路由分组 Group 的内部实现 与 块空间 { } 的应用

通过这篇 [Gin] 单文件极简 HTTP Server 流程分析 ( gin-gonic/gin ) 

我们知道了 gin.go 中的 Engine 继承有 routergroup.go 中的 RouterGroup 结构,从而获得其所有方法。

RouterGroup 结构有一个方法 Group 是处理分组的,返回新的路由分组实例,分组的目的可以是出于路径归类 或者 为了使用相同的中间件。

// routergroup.go

//
Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. // For example, all the routes that use a common middleware for authorization could be grouped. func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { return &RouterGroup{ Handlers: group.combineHandlers(handlers), basePath: group.calculateAbsolutePath(relativePath), engine: group.engine, } } // BasePath returns the base path of router group. // For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api". func (group *RouterGroup) BasePath() string { return group.basePath } func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes { absolutePath := group.calculateAbsolutePath(relativePath) handlers = group.combineHandlers(handlers) group.engine.addRoute(httpMethod, absolutePath, handlers) return group.returnObj() }

应用:

// example.go

func main() {
    router := gin.Default()

    // Simple group: v1
    v1 := router.Group("/v1")
{ v1.POST(
"/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // Simple group: v2 v2 := router.Group("/v2")
{ v2.POST(
"/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") }

Group 只是一个函数,上面花括号是代表中间的语句属于一个空间内,不受外界干扰,C语言中也有块空间的语法。

Link:https://www.cnblogs.com/farwish/p/12707649.html

原文地址:https://www.cnblogs.com/farwish/p/12707649.html