query.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. var err error
  47. f, props, err = fieldByProtoName(m, fieldName)
  48. if err != nil {
  49. return err
  50. } else if !f.IsValid() {
  51. grpclog.Printf("field not found in %T: %s", msg, strings.Join(fieldPath, "."))
  52. return nil
  53. }
  54. switch f.Kind() {
  55. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64:
  56. if !isLast {
  57. return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], "."))
  58. }
  59. m = f
  60. case reflect.Slice:
  61. // TODO(yugui) Support []byte
  62. if !isLast {
  63. return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, "."))
  64. }
  65. return populateRepeatedField(f, values, props)
  66. case reflect.Ptr:
  67. if f.IsNil() {
  68. m = reflect.New(f.Type().Elem())
  69. f.Set(m.Convert(f.Type()))
  70. }
  71. m = f.Elem()
  72. continue
  73. case reflect.Struct:
  74. m = f
  75. continue
  76. default:
  77. return fmt.Errorf("unexpected type %s in %T", f.Type(), msg)
  78. }
  79. }
  80. switch len(values) {
  81. case 0:
  82. return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, "."))
  83. case 1:
  84. default:
  85. grpclog.Printf("too many field values: %s", strings.Join(fieldPath, "."))
  86. }
  87. return populateField(m, values[0], props)
  88. }
  89. // fieldByProtoName looks up a field whose corresponding protobuf field name is "name".
  90. // "m" must be a struct value. It returns zero reflect.Value if no such field found.
  91. func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties, error) {
  92. props := proto.GetProperties(m.Type())
  93. // look up field name in oneof map
  94. if op, ok := props.OneofTypes[name]; ok {
  95. v := reflect.New(op.Type.Elem())
  96. field := m.Field(op.Field)
  97. if !field.IsNil() {
  98. return reflect.Value{}, nil, fmt.Errorf("field already set for %s oneof", props.Prop[op.Field].OrigName)
  99. }
  100. field.Set(v)
  101. return v.Elem().Field(0), op.Prop, nil
  102. }
  103. for _, p := range props.Prop {
  104. if p.OrigName == name {
  105. return m.FieldByName(p.Name), p, nil
  106. }
  107. }
  108. return reflect.Value{}, nil, nil
  109. }
  110. func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error {
  111. elemType := f.Type().Elem()
  112. // is the destination field a slice of an enumeration type?
  113. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  114. return populateFieldEnumRepeated(f, values, enumValMap)
  115. }
  116. conv, ok := convFromType[elemType.Kind()]
  117. if !ok {
  118. return fmt.Errorf("unsupported field type %s", elemType)
  119. }
  120. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  121. for i, v := range values {
  122. result := conv.Call([]reflect.Value{reflect.ValueOf(v)})
  123. if err := result[1].Interface(); err != nil {
  124. return err.(error)
  125. }
  126. f.Index(i).Set(result[0].Convert(f.Index(i).Type()))
  127. }
  128. return nil
  129. }
  130. func populateField(f reflect.Value, value string, props *proto.Properties) error {
  131. // Handle well known type
  132. type wkt interface {
  133. XXX_WellKnownType() string
  134. }
  135. if wkt, ok := f.Addr().Interface().(wkt); ok {
  136. switch wkt.XXX_WellKnownType() {
  137. case "Timestamp":
  138. if value == "null" {
  139. f.Field(0).SetInt(0)
  140. f.Field(1).SetInt(0)
  141. return nil
  142. }
  143. t, err := time.Parse(time.RFC3339Nano, value)
  144. if err != nil {
  145. return fmt.Errorf("bad Timestamp: %v", err)
  146. }
  147. f.Field(0).SetInt(int64(t.Unix()))
  148. f.Field(1).SetInt(int64(t.Nanosecond()))
  149. return nil
  150. }
  151. }
  152. // is the destination field an enumeration type?
  153. if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil {
  154. return populateFieldEnum(f, value, enumValMap)
  155. }
  156. conv, ok := convFromType[f.Kind()]
  157. if !ok {
  158. return fmt.Errorf("unsupported field type %T", f)
  159. }
  160. result := conv.Call([]reflect.Value{reflect.ValueOf(value)})
  161. if err := result[1].Interface(); err != nil {
  162. return err.(error)
  163. }
  164. f.Set(result[0].Convert(f.Type()))
  165. return nil
  166. }
  167. func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) {
  168. // see if it's an enumeration string
  169. if enumVal, ok := enumValMap[value]; ok {
  170. return reflect.ValueOf(enumVal).Convert(t), nil
  171. }
  172. // check for an integer that matches an enumeration value
  173. eVal, err := strconv.Atoi(value)
  174. if err != nil {
  175. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  176. }
  177. for _, v := range enumValMap {
  178. if v == int32(eVal) {
  179. return reflect.ValueOf(eVal).Convert(t), nil
  180. }
  181. }
  182. return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t)
  183. }
  184. func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error {
  185. cval, err := convertEnum(value, f.Type(), enumValMap)
  186. if err != nil {
  187. return err
  188. }
  189. f.Set(cval)
  190. return nil
  191. }
  192. func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error {
  193. elemType := f.Type().Elem()
  194. f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type()))
  195. for i, v := range values {
  196. result, err := convertEnum(v, elemType, enumValMap)
  197. if err != nil {
  198. return err
  199. }
  200. f.Index(i).Set(result)
  201. }
  202. return nil
  203. }
  204. var (
  205. convFromType = map[reflect.Kind]reflect.Value{
  206. reflect.String: reflect.ValueOf(String),
  207. reflect.Bool: reflect.ValueOf(Bool),
  208. reflect.Float64: reflect.ValueOf(Float64),
  209. reflect.Float32: reflect.ValueOf(Float32),
  210. reflect.Int64: reflect.ValueOf(Int64),
  211. reflect.Int32: reflect.ValueOf(Int32),
  212. reflect.Uint64: reflect.ValueOf(Uint64),
  213. reflect.Uint32: reflect.ValueOf(Uint32),
  214. // TODO(yugui) Support []byte
  215. }
  216. )