Go web框架gin跨域实现

package router

import (
    "github.com/gin-gonic/gin"
    "cdn-server/controller"
)

func ConfigRouter(r gin.IRouter) {
    //app 接口

    r.Use(CORSMiddleware())

    app := r.Group("/api/")

    {
        app.GET("libraries", controller.LibrariesList)
        app.GET("libraries/:name", controller.LibrariesInfo)
    }

}

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        origin := c.Request.Header.Get("origin")
        c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, XMLHttpRequest, " +
            "Accept-Encoding, X-CSRF-Token, Authorization")
        if c.Request.Method == "OPTIONS" {
            c.String(200, "ok")
            return
        }
        c.Next()
    }
}