protobuf.go 933 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. "errors"
  7. "io/ioutil"
  8. "net/http"
  9. "google.golang.org/protobuf/proto"
  10. )
  11. type protobufBinding struct{}
  12. func (protobufBinding) Name() string {
  13. return "protobuf"
  14. }
  15. func (b protobufBinding) Bind(req *http.Request, obj any) error {
  16. buf, err := ioutil.ReadAll(req.Body)
  17. if err != nil {
  18. return err
  19. }
  20. return b.BindBody(buf, obj)
  21. }
  22. func (protobufBinding) BindBody(body []byte, obj any) error {
  23. msg, ok := obj.(proto.Message)
  24. if !ok {
  25. return errors.New("obj is not ProtoMessage")
  26. }
  27. if err := proto.Unmarshal(body, msg); err != nil {
  28. return err
  29. }
  30. // Here it's same to return validate(obj), but util now we can't add
  31. // `binding:""` to the struct which automatically generate by gen-proto
  32. return nil
  33. // return validate(obj)
  34. }