object.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package query
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. // Object represents the encoding of Query structures and unions. A Query
  7. // object is a representation of a mapping of string keys to arbitrary
  8. // values where there is a fixed set of keys whose values each have their
  9. // own known type. A serialized object might look like the following:
  10. //
  11. // ObjectName.Foo=value
  12. // &ObjectName.Bar=5
  13. type Object struct {
  14. // The query values to add the object to.
  15. values url.Values
  16. // The object's prefix, which includes the names of all parent structures
  17. // and ends with the name of the object. For example, the prefix might be
  18. // "ParentStructure.ObjectName". This prefix will be used to form the full
  19. // keys for each member of the object. For example, a member might have the
  20. // key "ParentStructure.ObjectName.MemberName".
  21. //
  22. // While this is currently represented as a string that gets added to, it
  23. // could also be represented as a stack that only gets condensed into a
  24. // string when a finalized key is created. This could potentially reduce
  25. // allocations.
  26. prefix string
  27. }
  28. func newObject(values url.Values, prefix string) *Object {
  29. return &Object{
  30. values: values,
  31. prefix: prefix,
  32. }
  33. }
  34. // Key adds the given named key to the Query object.
  35. // Returns a Value encoder that should be used to encode a Query value type.
  36. func (o *Object) Key(name string) Value {
  37. return o.key(name, false)
  38. }
  39. // KeyWithValues adds the given named key to the Query object.
  40. // Returns a Value encoder that should be used to encode a Query list of values.
  41. func (o *Object) KeyWithValues(name string) Value {
  42. return o.keyWithValues(name, false)
  43. }
  44. // FlatKey adds the given named key to the Query object.
  45. // Returns a Value encoder that should be used to encode a Query value type. The
  46. // value will be flattened if it is a map or array.
  47. func (o *Object) FlatKey(name string) Value {
  48. return o.key(name, true)
  49. }
  50. func (o *Object) key(name string, flatValue bool) Value {
  51. if o.prefix != "" {
  52. return newValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue)
  53. }
  54. return newValue(o.values, name, flatValue)
  55. }
  56. func (o *Object) keyWithValues(name string, flatValue bool) Value {
  57. if o.prefix != "" {
  58. return newAppendValue(o.values, fmt.Sprintf("%s.%s", o.prefix, name), flatValue)
  59. }
  60. return newAppendValue(o.values, name, flatValue)
  61. }