gin router过程

func main() {
    // Creates a router without any middleware by default
    r := gin.New()

    //routegroup.go 中routegroup结构有一个字段:handlers保存所有middleware
    // Global middleware : 
    r.Use(gin.Logger())    
    r.Use(gin.Recovery())

    // Per route middleware, you can add as many as you desire.
    //所有handers加上routegroup.handlers中的handlers,一起存储到tree(参考 httprouter)中
    //当请求过来时,依次执行以上所有的handlers
    r.GET("/benchmark", MyBenchLogger(), benchEndpoint) 

    // Authorization group
    // authorized := r.Group("/", AuthRequired())等价于 authorized := r.Group("/")、authorized.Use(AuthRequired())
    authorized := r.Group("/")
    authorized.Use(AuthRequired())
    {
        //请求/login时,将执行AuthRequired、loginEndpoint
        authorized.POST("/login", loginEndpoint) 
        //请求/submit时,将执行AuthRequired、submitEndpoint
        authorized.POST("/submit", submitEndpoint)
        authorized.POST("/read", readEndpoint)

        // nested group
        testing := authorized.Group("testing")
        testing.GET("/analytics", analyticsEndpoint)
    }

    // Listen and server on 0.0.0.0:8080
    r.Run(":8080")
}

关于 liuzhantao

北京互联网求职群:168047123
此条目发表在 gin 分类目录。将固定链接加入收藏夹。