package api_conn import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) func Api() { // 创建一个默认的Gin引擎 r := gin.Default() // 使用CORS中间件 r.Use(CORSMiddleware()) // 添加全局中间件,用于记录请求日志 r.Use(func(c *gin.Context) { fmt.Println("Middleware - Request URL:", c.Request.URL) c.Next() }) // 使用路由组,并应用中间件 api := r.Group("/api/v1/") // 配置认证中间件 api.Use(authMiddleware) // 配置接口路由 //星座接口 api.POST("/constellation", constellation) // 添加 NoRoute 处理,自定义404返回 r.NoRoute(func(c *gin.Context) { // 创建一个 error 实例 error_type := Data_err{ Msg: "访问受限", Code: "2001", Err: "Not Found", } c.JSON(http.StatusNotFound, error_type) }) // 启动HTTP服务器,默认监听在 :8080 r.Run("0.0.0.0:52000") } // CORSMiddleware 处理跨域请求的中间件 func CORSMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) return } c.Next() } }