query.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package runtime
  2. import (
  3. "fmt"
  4. "net/url"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/golang/protobuf/proto"
  10. "github.com/grpc-ecosystem/grpc-gateway/utilities"
  11. "google.golang.org/grpc/grpclog"
  12. )
  13. // PopulateQueryParameters populates "values" into "msg".
  14. // A value is ignored if its key starts with one of the elements in "filter".
  15. func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
  16. for key, values := range values {
  17. fieldPath := strings.Split(key, ".")
  18. if filter.HasCommonPrefix(fieldPath) {
  19. continue
  20. }
  21. if err := populateFieldValueFromPath(msg, fieldPath, values); err != nil {
  22. return err
  23. }
  24. }
  25. return nil
  26. }
  27. // PopulateFieldFromPath sets a value in a nested Protobuf structure.
  28. // It instantiates missing protobuf fields as it goes.
  29. func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error {
  30. fieldPath := strings.Split(fieldPathString, ".")
  31. return populateFieldValueFromPath(msg, fieldPath, []string{value})
  32. }
  33. func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error {
  34. m := reflect.ValueOf(msg)
  35. if m.Kind() != reflect.Ptr {
  36. return fmt.Errorf("unexpected type %T: %v", msg, msg)
  37. }
  38. var props *proto.Properties
  39. m = m.Elem()
  40. for i, fieldName := range fieldPath {
  41. isLast := i == len(fieldPath)-1
  42. if !isLast && m.Kind() != reflect.Struct {
  43. return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, "."))
  44. }
  45. var f reflect.Value
  46. f, props = fieldByProtoName(m, fieldName)
  47. if !f.IsValid() {
  48. grpclog.Printf("field not found in %T: %s", msg, strings.Join(fieldPath, "."))
  49. return nil
  50. }
  51. switch f.Kind() {
  52. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64:
  53. if !isLast {
  54. return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], "."))
  55. }
  56. m = f
  57. case reflect.Slice:
  58. // TODO(yugui) Support []byte
  59. if !isLast {
  60. return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, "."))
  61. }
  62. return populateRepeatedField(f, values, props)
  63. case reflect.Ptr:
  64. if f.IsNil() {
  65. m = reflect.New(f.Type().Elem())
  66. f.Set(m.Convert(f.Type()))
  67. }
  68. m = f.Elem()
  69. continue
  70. case reflect.Struct:
  71. m = f
  72. continue
  73. default:
  74. return fmt.Errorf("unexpected type %s in %T", f.Type(), msg)
  75. }
  76. }
  77. switch len(values) {
  78. case 0:
  79. return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, "."))
  80. case 1:
  81. default:
  82. grpclog.Printf("too many field values: %s", strings.Join(fieldPath, "."))
  83. }
  84. return populateField(m, values[0], props)
  85. }
  86. // fieldByProtoName looks up a field whose corresponding protobuf field name is "name".
  87. // "m" must be a struct value. It returns zero reflect.Value if no such field found.
  88. func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties) {
  89. props := proto.GetProperties(m.Type())
  90. for _, p := range props.Prop {
  91. if p.OrigName == name {
  92. return m.FieldByName(p.Name), p
  93. }
  94. }
  95. return reflect.Value{}, nil
  96. }
  97. func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error {
  98. elemType := f.Type().Elem()
  99. // is the destination field a slice of an enumeration type?
  100. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  101. return populateFieldEnumRepeated(f, values, enumValMap)
  102. }
  103. conv, ok := convFromType[elemType.Kind()]
  104. if !ok {
  105. return fmt.Errorf("unsupported field type %s", elemType)
  106. }
  107. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  108. for i, v := range values {
  109. result := conv.Call([]reflect.Value{reflect.ValueOf(v)})
  110. if err := result[1].Interface(); err != nil {
  111. return err.(error)
  112. }
  113. f.Index(i).Set(result[0].Convert(f.Index(i).Type()))
  114. }
  115. return nil
  116. }
  117. func populateField(f reflect.Value, value string, props *proto.Properties) error {
  118. // Handle well known type
  119. type wkt interface {
  120. XXX_WellKnownType() string
  121. }
  122. if wkt, ok := f.Addr().Interface().(wkt); ok {
  123. switch wkt.XXX_WellKnownType() {
  124. case "Timestamp":
  125. if value == "null" {
  126. f.Field(0).SetInt(0)
  127. f.Field(1).SetInt(0)
  128. return nil
  129. }
  130. t, err := time.Parse(time.RFC3339Nano, value)
  131. if err != nil {
  132. return fmt.Errorf("bad Timestamp: %v", err)
  133. }
  134. f.Field(0).SetInt(int64(t.Unix()))
  135. f.Field(1).SetInt(int64(t.Nanosecond()))
  136. return nil
  137. }
  138. }
  139. // is the destination field an enumeration type?
  140. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  141. return populateFieldEnum(f, value, enumValMap)
  142. }
  143. conv, ok := convFromType[f.Kind()]
  144. if !ok {
  145. return fmt.Errorf("unsupported field type %T", f)
  146. }
  147. result := conv.Call([]reflect.Value{reflect.ValueOf(value)})
  148. if err := result[1].Interface(); err != nil {
  149. return err.(error)
  150. }
  151. f.Set(result[0].Convert(f.Type()))
  152. return nil
  153. }
  154. func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) {
  155. // see if it's an enumeration string
  156. if enumVal, ok := enumValMap[value]; ok {
  157. return reflect.ValueOf(enumVal).Convert(t), nil
  158. }
  159. // check for an integer that matches an enumeration value
  160. eVal, err := strconv.Atoi(value)
  161. if err != nil {
  162. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  163. }
  164. for _, v := range enumValMap {
  165. if v == int32(eVal) {
  166. return reflect.ValueOf(eVal).Convert(t), nil
  167. }
  168. }
  169. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  170. }
  171. func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error {
  172. cval, err := convertEnum(value, f.Type(), enumValMap)
  173. if err != nil {
  174. return err
  175. }
  176. f.Set(cval)
  177. return nil
  178. }
  179. func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error {
  180. elemType := f.Type().Elem()
  181. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  182. for i, v := range values {
  183. result, err := convertEnum(v, elemType, enumValMap)
  184. if err != nil {
  185. return err
  186. }
  187. f.Index(i).Set(result)
  188. }
  189. return nil
  190. }
  191. var (
  192. convFromType = map[reflect.Kind]reflect.Value{
  193. reflect.String: reflect.ValueOf(String),
  194. reflect.Bool: reflect.ValueOf(Bool),
  195. reflect.Float64: reflect.ValueOf(Float64),
  196. reflect.Float32: reflect.ValueOf(Float32),
  197. reflect.Int64: reflect.ValueOf(Int64),
  198. reflect.Int32: reflect.ValueOf(Int32),
  199. reflect.Uint64: reflect.ValueOf(Uint64),
  200. reflect.Uint32: reflect.ValueOf(Uint32),
  201. // TODO(yugui) Support []byte
  202. }
  203. )