...

Source file src/github.com/gin-gonic/gin/binding/protobuf.go

Documentation: github.com/gin-gonic/gin/binding

     1  // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
     2  // Use of this source code is governed by a MIT style
     3  // license that can be found in the LICENSE file.
     4  
     5  package binding
     6  
     7  import (
     8  	"errors"
     9  	"io"
    10  	"net/http"
    11  
    12  	"google.golang.org/protobuf/proto"
    13  )
    14  
    15  type protobufBinding struct{}
    16  
    17  func (protobufBinding) Name() string {
    18  	return "protobuf"
    19  }
    20  
    21  func (b protobufBinding) Bind(req *http.Request, obj any) error {
    22  	buf, err := io.ReadAll(req.Body)
    23  	if err != nil {
    24  		return err
    25  	}
    26  	return b.BindBody(buf, obj)
    27  }
    28  
    29  func (protobufBinding) BindBody(body []byte, obj any) error {
    30  	msg, ok := obj.(proto.Message)
    31  	if !ok {
    32  		return errors.New("obj is not ProtoMessage")
    33  	}
    34  	if err := proto.Unmarshal(body, msg); err != nil {
    35  		return err
    36  	}
    37  	// Here it's same to return validate(obj), but util now we can't add
    38  	// `binding:""` to the struct which automatically generate by gen-proto
    39  	return nil
    40  	// return validate(obj)
    41  }
    42  

View as plain text