query.go

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