query_encoder.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package httptt
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "net/url"
  7. "reflect"
  8. "strings"
  9. "kpt-tmr-group/pkg/xerr"
  10. "github.com/golang/protobuf/proto"
  11. )
  12. type wkt interface {
  13. XXX_WellKnownType() string
  14. }
  15. var wktType = reflect.TypeOf((*wkt)(nil)).Elem()
  16. func MarshalQueryPB(pb proto.Message) *url.Values {
  17. fields := make(url.Values)
  18. target := reflect.ValueOf(pb).Elem()
  19. props := proto.GetProperties(target.Type())
  20. for i := 0; i < target.NumField(); i++ {
  21. ft := target.Type().Field(i)
  22. if strings.HasPrefix(ft.Name, "XXX_") || ft.Anonymous {
  23. continue
  24. }
  25. // unexported field
  26. if strings.ToUpper(ft.Name[:1]) != ft.Name[:1] {
  27. continue
  28. }
  29. if err := setFields(&fields, target.Field(i), props.Prop[i]); err != nil {
  30. panic(err)
  31. }
  32. }
  33. return &fields
  34. }
  35. func setFields(fields *url.Values, target reflect.Value, prop *proto.Properties) error {
  36. if target.Kind() == reflect.Slice && target.Type().Elem().Kind() != reflect.Uint8 {
  37. for i := 0; i < target.Len(); i++ {
  38. if err := setFields(fields, target.Index(i), prop); err != nil {
  39. return xerr.WithStack(err)
  40. }
  41. }
  42. return nil
  43. }
  44. // Handle well-known types.
  45. // Most are handled up in marshalObject (because 99% are messages).
  46. if target.Type().Implements(wktType) {
  47. wkt := target.Interface().(wkt)
  48. switch wkt.XXX_WellKnownType() {
  49. case "NullValue":
  50. appendFields(fields, prop, "null")
  51. return nil
  52. }
  53. }
  54. if prop.Enum != "" {
  55. appendFields(fields, prop, target.Interface().(fmt.Stringer).String())
  56. return nil
  57. }
  58. if target.Kind() == reflect.Float32 || target.Kind() == reflect.Float64 {
  59. f := target.Float()
  60. var sval string
  61. switch {
  62. case math.IsInf(f, 1):
  63. sval = `"Infinity"`
  64. case math.IsInf(f, -1):
  65. sval = `"-Infinity"`
  66. case math.IsNaN(f):
  67. sval = `"NaN"`
  68. }
  69. if sval != "" {
  70. appendFields(fields, prop, sval)
  71. return nil
  72. }
  73. }
  74. b, err := json.Marshal(target.Interface())
  75. if err != nil {
  76. return xerr.WithStack(err)
  77. }
  78. appendFields(fields, prop, string(b))
  79. return nil
  80. }
  81. func appendFields(v *url.Values, prop *proto.Properties, value string) {
  82. key := prop.JSONName
  83. if key == "" {
  84. key = prop.OrigName
  85. }
  86. v.Add(key, value)
  87. }