feat: refactor application to use Gin framework, update routing and middleware handling

This commit is contained in:
王锦强
2025-03-15 12:39:17 +08:00
parent cab289dabf
commit 6fa5c1f467
13 changed files with 314 additions and 279 deletions

View File

@@ -1,22 +1,22 @@
package middleware
import "net/http"
import "github.com/gin-gonic/gin"
// CORS 处理跨域资源共享
func CORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
// 设置CORS响应头
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
// 如果是预检请求直接返回200
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
return
}
// 继续下一个处理器
next.ServeHTTP(w, r)
})
c.Next()
}
}