protobuf.go 853 B

123456789101112131415161718192021222324252627282930313233343536
  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. package binding
  5. import (
  6. "io"
  7. "net/http"
  8. "github.com/golang/protobuf/proto"
  9. )
  10. type protobufBinding struct{}
  11. func (protobufBinding) Name() string {
  12. return "protobuf"
  13. }
  14. func (b protobufBinding) Bind(req *http.Request, obj interface{}) error {
  15. buf, err := io.ReadAll(req.Body)
  16. if err != nil {
  17. return err
  18. }
  19. return b.BindBody(buf, obj)
  20. }
  21. func (protobufBinding) BindBody(body []byte, obj interface{}) error {
  22. if err := proto.Unmarshal(body, obj.(proto.Message)); err != nil {
  23. return err
  24. }
  25. // Here it's same to return validate(obj), but util now we can't add
  26. // `binding:""` to the struct which automatically generate by gen-proto
  27. return nil
  28. // return validate(obj)
  29. }