初始化
This commit is contained in:
36
server/middleware/cors.go
Normal file
36
server/middleware/cors.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Package middleware 提供HTTP中间件
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORS 跨域资源共享中间件
|
||||
func CORS() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, X-Requested-With")
|
||||
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type")
|
||||
c.Header("Access-Control-Max-Age", "86400")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// UTF8ContentType 确保JSON响应使用UTF-8编码
|
||||
func UTF8ContentType() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
// 为JSON响应添加charset
|
||||
contentType := c.Writer.Header().Get("Content-Type")
|
||||
if contentType == "application/json" {
|
||||
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user