26 lines
842 B
Go
26 lines
842 B
Go
// 中间件:Gin 的中间件是 func(*gin.Context),通过 c.Next() 控制执行链
|
||
// 执行顺序:请求进入 → 中间件1(c.Next前) → 中间件2(c.Next前) → Handler → 中间件2(c.Next后) → 中间件1(c.Next后) → 响应
|
||
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// CORS 跨域中间件,允许 H5 调试时跨域访问
|
||
func CORS() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
c.Header("Access-Control-Allow-Origin", "*")
|
||
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
|
||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type")
|
||
|
||
if c.Request.Method == "OPTIONS" {
|
||
c.AbortWithStatus(http.StatusNoContent)
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|