本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

321 lines
8.5KB

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package query implements encoding of structs into URL query parameters.
  5. //
  6. // As a simple example:
  7. //
  8. // type Options struct {
  9. // Query string `url:"q"`
  10. // ShowAll bool `url:"all"`
  11. // Page int `url:"page"`
  12. // }
  13. //
  14. // opt := Options{ "foo", true, 2 }
  15. // v, _ := query.Values(opt)
  16. // fmt.Print(v.Encode()) // will output: "q=foo&all=true&page=2"
  17. //
  18. // The exact mapping between Go values and url.Values is described in the
  19. // documentation for the Values() function.
  20. package query
  21. import (
  22. "bytes"
  23. "fmt"
  24. "net/url"
  25. "reflect"
  26. "strconv"
  27. "strings"
  28. "time"
  29. )
  30. var timeType = reflect.TypeOf(time.Time{})
  31. var encoderType = reflect.TypeOf(new(Encoder)).Elem()
  32. // Encoder is an interface implemented by any type that wishes to encode
  33. // itself into URL values in a non-standard way.
  34. type Encoder interface {
  35. EncodeValues(key string, v *url.Values) error
  36. }
  37. // Values returns the url.Values encoding of v.
  38. //
  39. // Values expects to be passed a struct, and traverses it recursively using the
  40. // following encoding rules.
  41. //
  42. // Each exported struct field is encoded as a URL parameter unless
  43. //
  44. // - the field's tag is "-", or
  45. // - the field is empty and its tag specifies the "omitempty" option
  46. //
  47. // The empty values are false, 0, any nil pointer or interface value, any array
  48. // slice, map, or string of length zero, and any time.Time that returns true
  49. // for IsZero().
  50. //
  51. // The URL parameter name defaults to the struct field name but can be
  52. // specified in the struct field's tag value. The "url" key in the struct
  53. // field's tag value is the key name, followed by an optional comma and
  54. // options. For example:
  55. //
  56. // // Field is ignored by this package.
  57. // Field int `url:"-"`
  58. //
  59. // // Field appears as URL parameter "myName".
  60. // Field int `url:"myName"`
  61. //
  62. // // Field appears as URL parameter "myName" and the field is omitted if
  63. // // its value is empty
  64. // Field int `url:"myName,omitempty"`
  65. //
  66. // // Field appears as URL parameter "Field" (the default), but the field
  67. // // is skipped if empty. Note the leading comma.
  68. // Field int `url:",omitempty"`
  69. //
  70. // For encoding individual field values, the following type-dependent rules
  71. // apply:
  72. //
  73. // Boolean values default to encoding as the strings "true" or "false".
  74. // Including the "int" option signals that the field should be encoded as the
  75. // strings "1" or "0".
  76. //
  77. // time.Time values default to encoding as RFC3339 timestamps. Including the
  78. // "unix" option signals that the field should be encoded as a Unix time (see
  79. // time.Unix())
  80. //
  81. // Slice and Array values default to encoding as multiple URL values of the
  82. // same name. Including the "comma" option signals that the field should be
  83. // encoded as a single comma-delimited value. Including the "space" option
  84. // similarly encodes the value as a single space-delimited string. Including
  85. // the "semicolon" option will encode the value as a semicolon-delimited string.
  86. // Including the "brackets" option signals that the multiple URL values should
  87. // have "[]" appended to the value name. "numbered" will append a number to
  88. // the end of each incidence of the value name, example:
  89. // name0=value0&name1=value1, etc.
  90. //
  91. // Anonymous struct fields are usually encoded as if their inner exported
  92. // fields were fields in the outer struct, subject to the standard Go
  93. // visibility rules. An anonymous struct field with a name given in its URL
  94. // tag is treated as having that name, rather than being anonymous.
  95. //
  96. // Non-nil pointer values are encoded as the value pointed to.
  97. //
  98. // Nested structs are encoded including parent fields in value names for
  99. // scoping. e.g:
  100. //
  101. // "user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO"
  102. //
  103. // All other values are encoded using their default string representation.
  104. //
  105. // Multiple fields that encode to the same URL parameter name will be included
  106. // as multiple URL values of the same name.
  107. func Values(v interface{}) (url.Values, error) {
  108. values := make(url.Values)
  109. val := reflect.ValueOf(v)
  110. for val.Kind() == reflect.Ptr {
  111. if val.IsNil() {
  112. return values, nil
  113. }
  114. val = val.Elem()
  115. }
  116. if v == nil {
  117. return values, nil
  118. }
  119. if val.Kind() != reflect.Struct {
  120. return nil, fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind())
  121. }
  122. err := reflectValue(values, val, "")
  123. return values, err
  124. }
  125. // reflectValue populates the values parameter from the struct fields in val.
  126. // Embedded structs are followed recursively (using the rules defined in the
  127. // Values function documentation) breadth-first.
  128. func reflectValue(values url.Values, val reflect.Value, scope string) error {
  129. var embedded []reflect.Value
  130. typ := val.Type()
  131. for i := 0; i < typ.NumField(); i++ {
  132. sf := typ.Field(i)
  133. if sf.PkgPath != "" && !sf.Anonymous { // unexported
  134. continue
  135. }
  136. sv := val.Field(i)
  137. tag := sf.Tag.Get("url")
  138. if tag == "-" {
  139. continue
  140. }
  141. name, opts := parseTag(tag)
  142. if name == "" {
  143. if sf.Anonymous && sv.Kind() == reflect.Struct {
  144. // save embedded struct for later processing
  145. embedded = append(embedded, sv)
  146. continue
  147. }
  148. name = sf.Name
  149. }
  150. if scope != "" {
  151. name = scope + "[" + name + "]"
  152. }
  153. if opts.Contains("omitempty") && isEmptyValue(sv) {
  154. continue
  155. }
  156. if sv.Type().Implements(encoderType) {
  157. if !reflect.Indirect(sv).IsValid() {
  158. sv = reflect.New(sv.Type().Elem())
  159. }
  160. m := sv.Interface().(Encoder)
  161. if err := m.EncodeValues(name, &values); err != nil {
  162. return err
  163. }
  164. continue
  165. }
  166. if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array {
  167. var del byte
  168. if opts.Contains("comma") {
  169. del = ','
  170. } else if opts.Contains("space") {
  171. del = ' '
  172. } else if opts.Contains("semicolon") {
  173. del = ';'
  174. } else if opts.Contains("brackets") {
  175. name = name + "[]"
  176. }
  177. if del != 0 {
  178. s := new(bytes.Buffer)
  179. first := true
  180. for i := 0; i < sv.Len(); i++ {
  181. if first {
  182. first = false
  183. } else {
  184. s.WriteByte(del)
  185. }
  186. s.WriteString(valueString(sv.Index(i), opts))
  187. }
  188. values.Add(name, s.String())
  189. } else {
  190. for i := 0; i < sv.Len(); i++ {
  191. k := name
  192. if opts.Contains("numbered") {
  193. k = fmt.Sprintf("%s%d", name, i)
  194. }
  195. values.Add(k, valueString(sv.Index(i), opts))
  196. }
  197. }
  198. continue
  199. }
  200. for sv.Kind() == reflect.Ptr {
  201. if sv.IsNil() {
  202. break
  203. }
  204. sv = sv.Elem()
  205. }
  206. if sv.Type() == timeType {
  207. values.Add(name, valueString(sv, opts))
  208. continue
  209. }
  210. if sv.Kind() == reflect.Struct {
  211. reflectValue(values, sv, name)
  212. continue
  213. }
  214. values.Add(name, valueString(sv, opts))
  215. }
  216. for _, f := range embedded {
  217. if err := reflectValue(values, f, scope); err != nil {
  218. return err
  219. }
  220. }
  221. return nil
  222. }
  223. // valueString returns the string representation of a value.
  224. func valueString(v reflect.Value, opts tagOptions) string {
  225. for v.Kind() == reflect.Ptr {
  226. if v.IsNil() {
  227. return ""
  228. }
  229. v = v.Elem()
  230. }
  231. if v.Kind() == reflect.Bool && opts.Contains("int") {
  232. if v.Bool() {
  233. return "1"
  234. }
  235. return "0"
  236. }
  237. if v.Type() == timeType {
  238. t := v.Interface().(time.Time)
  239. if opts.Contains("unix") {
  240. return strconv.FormatInt(t.Unix(), 10)
  241. }
  242. return t.Format(time.RFC3339)
  243. }
  244. return fmt.Sprint(v.Interface())
  245. }
  246. // isEmptyValue checks if a value should be considered empty for the purposes
  247. // of omitting fields with the "omitempty" option.
  248. func isEmptyValue(v reflect.Value) bool {
  249. switch v.Kind() {
  250. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  251. return v.Len() == 0
  252. case reflect.Bool:
  253. return !v.Bool()
  254. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  255. return v.Int() == 0
  256. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  257. return v.Uint() == 0
  258. case reflect.Float32, reflect.Float64:
  259. return v.Float() == 0
  260. case reflect.Interface, reflect.Ptr:
  261. return v.IsNil()
  262. }
  263. if v.Type() == timeType {
  264. return v.Interface().(time.Time).IsZero()
  265. }
  266. return false
  267. }
  268. // tagOptions is the string following a comma in a struct field's "url" tag, or
  269. // the empty string. It does not include the leading comma.
  270. type tagOptions []string
  271. // parseTag splits a struct field's url tag into its name and comma-separated
  272. // options.
  273. func parseTag(tag string) (string, tagOptions) {
  274. s := strings.Split(tag, ",")
  275. return s[0], s[1:]
  276. }
  277. // Contains checks whether the tagOptions contains the specified option.
  278. func (o tagOptions) Contains(option string) bool {
  279. for _, s := range o {
  280. if s == option {
  281. return true
  282. }
  283. }
  284. return false
  285. }
上海开阖软件有限公司 沪ICP备12045867号-1