main.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "net/http"
  4. "server/msg"
  5. "github.com/gin-contrib/cors"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gin-gonic/gin/binding"
  8. "google.golang.org/protobuf/proto"
  9. )
  10. func ParseProtoBuf(message proto.Message) gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. // 创建目标消息的新实例
  13. msg := proto.Clone(message)
  14. // 解析 Protobuf 数据
  15. if err := c.ShouldBindBodyWith(msg, binding.ProtoBuf); err != nil {
  16. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  17. "error": "Invalid protobuf data",
  18. "details": err.Error(),
  19. })
  20. return
  21. }
  22. // 存储解析后的消息
  23. c.Set("protobuf_data", msg)
  24. c.Next()
  25. }
  26. }
  27. // func ParseProtoBuf(c *gin.Context) {
  28. // // 1. 读取原始数据
  29. // body, err := io.ReadAll(c.Request.Body)
  30. // if err != nil {
  31. // c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Failed to read body"})
  32. // return
  33. // }
  34. // // 2. 存储原始二进制数据(供后续处理)
  35. // c.Set("protobuf_raw", body)
  36. // c.Next()
  37. // }
  38. func main() {
  39. r := gin.Default()
  40. // 使用 cors.New 创建中间件,并配置允许所有域的访问
  41. config := cors.DefaultConfig()
  42. config.AllowOrigins = []string{"*"} // 允许所有域
  43. config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
  44. config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Cookie"}
  45. config.AllowCredentials = true
  46. r.Use(cors.New(config))
  47. // r.GET("/", func(c *gin.Context) {
  48. // c.String(200, "Hello, Gin!")
  49. // })
  50. // r.GET("/json", func(c *gin.Context) {
  51. // c.JSON(200, gin.H{"message": "Hello, JSON!"})
  52. // })
  53. // r.GET("/test", func(c *gin.Context) {
  54. // c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
  55. // })
  56. r.POST("/ReqLogin", ParseProtoBuf(&msg.ReqLogin{}), ReqLogin)
  57. r.POST("/ReqRegister", ParseProtoBuf(&msg.ReqRegister{}), ReqRegister)
  58. r.POST("/ReqShop", ParseProtoBuf(&msg.ReqShop{}), ReqShop)
  59. r.Run(":8080") // 默认监听 :8080
  60. }