package main import ( "net/http" "server/msg" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "google.golang.org/protobuf/proto" ) func ParseProtoBuf(message proto.Message) gin.HandlerFunc { return func(c *gin.Context) { // 创建目标消息的新实例 msg := proto.Clone(message) // 解析 Protobuf 数据 if err := c.ShouldBindBodyWith(msg, binding.ProtoBuf); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ "error": "Invalid protobuf data", "details": err.Error(), }) return } // 存储解析后的消息 c.Set("protobuf_data", msg) c.Next() } } // func ParseProtoBuf(c *gin.Context) { // // 1. 读取原始数据 // body, err := io.ReadAll(c.Request.Body) // if err != nil { // c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Failed to read body"}) // return // } // // 2. 存储原始二进制数据(供后续处理) // c.Set("protobuf_raw", body) // c.Next() // } func main() { r := gin.Default() // 使用 cors.New 创建中间件,并配置允许所有域的访问 config := cors.DefaultConfig() config.AllowOrigins = []string{"*"} // 允许所有域 config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"} config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Cookie"} config.AllowCredentials = true r.Use(cors.New(config)) // r.GET("/", func(c *gin.Context) { // c.String(200, "Hello, Gin!") // }) // r.GET("/json", func(c *gin.Context) { // c.JSON(200, gin.H{"message": "Hello, JSON!"}) // }) // r.GET("/test", func(c *gin.Context) { // c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") // }) r.POST("/ReqLogin", ParseProtoBuf(&msg.ReqLogin{}), ReqLogin) r.POST("/ReqRegister", ParseProtoBuf(&msg.ReqRegister{}), ReqRegister) r.POST("/ReqShop", ParseProtoBuf(&msg.ReqShop{}), ReqShop) r.Run(":8080") // 默认监听 :8080 }