query.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package httpbinding
  2. import (
  3. "encoding/base64"
  4. "math"
  5. "math/big"
  6. "net/url"
  7. "strconv"
  8. )
  9. // QueryValue is used to encode query key values
  10. type QueryValue struct {
  11. query url.Values
  12. key string
  13. append bool
  14. }
  15. // NewQueryValue creates a new QueryValue which enables encoding
  16. // a query value into the given url.Values.
  17. func NewQueryValue(query url.Values, key string, append bool) QueryValue {
  18. return QueryValue{
  19. query: query,
  20. key: key,
  21. append: append,
  22. }
  23. }
  24. func (qv QueryValue) updateKey(value string) {
  25. if qv.append {
  26. qv.query.Add(qv.key, value)
  27. } else {
  28. qv.query.Set(qv.key, value)
  29. }
  30. }
  31. // Blob encodes v as a base64 query string value
  32. func (qv QueryValue) Blob(v []byte) {
  33. encodeToString := base64.StdEncoding.EncodeToString(v)
  34. qv.updateKey(encodeToString)
  35. }
  36. // Boolean encodes v as a query string value
  37. func (qv QueryValue) Boolean(v bool) {
  38. qv.updateKey(strconv.FormatBool(v))
  39. }
  40. // String encodes v as a query string value
  41. func (qv QueryValue) String(v string) {
  42. qv.updateKey(v)
  43. }
  44. // Byte encodes v as a query string value
  45. func (qv QueryValue) Byte(v int8) {
  46. qv.Long(int64(v))
  47. }
  48. // Short encodes v as a query string value
  49. func (qv QueryValue) Short(v int16) {
  50. qv.Long(int64(v))
  51. }
  52. // Integer encodes v as a query string value
  53. func (qv QueryValue) Integer(v int32) {
  54. qv.Long(int64(v))
  55. }
  56. // Long encodes v as a query string value
  57. func (qv QueryValue) Long(v int64) {
  58. qv.updateKey(strconv.FormatInt(v, 10))
  59. }
  60. // Float encodes v as a query string value
  61. func (qv QueryValue) Float(v float32) {
  62. qv.float(float64(v), 32)
  63. }
  64. // Double encodes v as a query string value
  65. func (qv QueryValue) Double(v float64) {
  66. qv.float(v, 64)
  67. }
  68. func (qv QueryValue) float(v float64, bitSize int) {
  69. switch {
  70. case math.IsNaN(v):
  71. qv.String(floatNaN)
  72. case math.IsInf(v, 1):
  73. qv.String(floatInfinity)
  74. case math.IsInf(v, -1):
  75. qv.String(floatNegInfinity)
  76. default:
  77. qv.updateKey(strconv.FormatFloat(v, 'f', -1, bitSize))
  78. }
  79. }
  80. // BigInteger encodes v as a query string value
  81. func (qv QueryValue) BigInteger(v *big.Int) {
  82. qv.updateKey(v.String())
  83. }
  84. // BigDecimal encodes v as a query string value
  85. func (qv QueryValue) BigDecimal(v *big.Float) {
  86. if i, accuracy := v.Int64(); accuracy == big.Exact {
  87. qv.Long(i)
  88. return
  89. }
  90. qv.updateKey(v.Text('e', -1))
  91. }