|
@@ -10,21 +10,42 @@ import (
|
|
|
"github.com/gin-gonic/gin"
|
|
|
"github.com/gin-gonic/gin/binding"
|
|
|
"github.com/name5566/leaf/log"
|
|
|
+ "google.golang.org/protobuf/proto"
|
|
|
)
|
|
|
|
|
|
-func ParseProtoBuf(c *gin.Context) {
|
|
|
- var req msg.ReqLogin
|
|
|
- if err := c.ShouldBindBodyWith(&req, binding.ProtoBuf); err != nil {
|
|
|
- c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
|
|
|
- "error": "Invalid protobuf data",
|
|
|
- "details": err.Error(),
|
|
|
- })
|
|
|
- return
|
|
|
+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()
|
|
|
}
|
|
|
- c.Set("protobuf_data", &req)
|
|
|
- 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()
|
|
|
|
|
@@ -49,8 +70,8 @@ func main() {
|
|
|
// c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
|
|
|
// })
|
|
|
|
|
|
- r.POST("/ReqLogin", ParseProtoBuf, ReqLogin)
|
|
|
- r.POST("/ReqRegister", ParseProtoBuf, ReqRegister)
|
|
|
+ r.POST("/ReqLogin", ParseProtoBuf(&msg.ReqLogin{}), ReqLogin)
|
|
|
+ r.POST("/ReqRegister", ParseProtoBuf(&msg.ReqRegister{}), ReqRegister)
|
|
|
r.Run(":8080") // 默认监听 :8080
|
|
|
}
|
|
|
|