// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
import (
"errors"
"io"
"net/http"
"google.golang.org/protobuf/proto"
)
type protobufBinding struct{}
func (protobufBinding) Name() string {
return "protobuf"
}
func (b protobufBinding) Bind(req *http.Request, obj any) error {
// ReadAll从req.Body读取直到出现错误或EOF,并返回它读取的数据
buf, err := io.ReadAll(req.Body)
if err != nil {
return err
}
return b.BindBody(buf, obj)
}
func (protobufBinding) BindBody(body []byte, obj any) error {
msg, ok := obj.(proto.Message)
if !ok {
return errors.New("obj is not ProtoMessage")
}
if err := proto.Unmarshal(body, msg); err != nil {
return err
}
// Here it's same to return validate(obj), but util now we can't add
// `binding:""` to the struct which automatically generate by gen-proto
// 在这里,返回validate(obj)是一样的,但util现在我们不能向gen proto自动生成的结构添加`binding:""`
return nil
// return validate(obj)
}
func (protobufBinding) BindBody1(body []byte, obj any) error {
msg, ok := obj.(proto.Message)
if !ok {
return errors.New("obj is not ProtoMessage")
}
// Unmarshal解析body中的有线格式消息,并将结果放在msg中。
if err := proto.Unmarshal(body, msg); err != nil {
return err
}
return nil
}
【Gin-v1.9.0源码阅读】binding/protobuf.go
猜你喜欢
转载自blog.csdn.net/qq2942713658/article/details/131017597
今日推荐
周排行