all_platform/api_conn/api.go
2025-03-16 23:57:25 +08:00

60 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()
}
}