bind.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package ginutil
  2. import (
  3. "net/http"
  4. "reflect"
  5. "kpt-tmr-group/pkg/jsonpb"
  6. "kpt-tmr-group/pkg/xerr"
  7. "github.com/gin-gonic/gin"
  8. "github.com/gin-gonic/gin/binding"
  9. "github.com/golang/protobuf/proto"
  10. "github.com/huandu/xstrings"
  11. )
  12. var camelQuery = &CamelQueryBinding{}
  13. // BindQuery with query params
  14. func BindQuery(c *gin.Context, obj interface{}) error {
  15. return c.ShouldBindWith(obj, camelQuery)
  16. }
  17. type CamelQueryBinding struct{}
  18. func (*CamelQueryBinding) Name() string {
  19. return "camel_query"
  20. }
  21. func (*CamelQueryBinding) Bind(req *http.Request, obj interface{}) error {
  22. values := req.URL.Query()
  23. if err := mapFormByTag(obj, values, "json"); err != nil {
  24. return err
  25. }
  26. return binding.Validator.ValidateStruct(obj)
  27. }
  28. type camelFormSource map[string][]string
  29. // TrySet tries to set a value by request's form source (like map[string][]string)
  30. func (form camelFormSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) {
  31. return setByForm(value, field, form, xstrings.FirstRuneToLower(xstrings.ToCamelCase(tagValue)), opt)
  32. }
  33. // BindProtoMessage with proto message from json body
  34. func BindProtoMessage(c *gin.Context, obj proto.Message) error {
  35. return c.ShouldBindWith(obj, protoMessageBindingFromBody)
  36. }
  37. var protoMessageBindingFromBody = &ProtoMessageBinding{}
  38. type ProtoMessageBinding struct{}
  39. func (*ProtoMessageBinding) Name() string {
  40. return "proto_message_binding"
  41. }
  42. func (*ProtoMessageBinding) Bind(req *http.Request, obj interface{}) error {
  43. pbMessage, ok := obj.(proto.Message)
  44. if !ok {
  45. return xerr.New("bind obj should be proto.Message")
  46. }
  47. if err := jsonpb.Unmarshal(req.Body, pbMessage); err != nil {
  48. return xerr.WithStack(err)
  49. }
  50. return binding.Validator.ValidateStruct(obj)
  51. }