路由

gin框架路由
创建于:2021年02月28日

路由定义

应用启动文件中定义的路由初始化函数(ApiInit)中定义路由方法

引入路由使用到的控制器包

package router

import (
    "github.com/gin-gonic/gin"
    "project/controller/v1"
)

func ApiInit(router *gin.Engine){

    router.POST("/login", v1.Login)

    router.GET("/article", v1.Article{}.GetList

}

访问静态资源文件
router.Static("路由规则", "静态资源目录")

router.Static("/statics", "./statics")

路由参数

// 此 handler 将匹配 /user/john 但不会匹配 /user/ 或者 /user
router.GET("/user/:name", func(c *gin.Context) {
    name := c.Param("name")
    c.String(http.StatusOK, "Hello %s", name)
})

允许跨域

在common公共库中设置请求头允许跨域访问

package common

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

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Token")
        c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(200)
        } else {
            c.Next()
        }
    }
}

路由中使用跨域方法

router.Use(common.Cors())

路由分组

package router

import (
    "github.com/gin-gonic/gin"
    "project/controller/v2"
)


func V2Init(router *gin.Engine){
    router.Use(common.Cors())

    V2 := router.Group("/V2")

    V2.Use(middleware.AuthMiddleWare())
    {
        V2.GET("/article", v2.Article{}.GetList)
    }

}