querystring.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jsonutils
  15. import (
  16. "net/url"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/sortedmap"
  22. "yunion.io/x/pkg/utils"
  23. )
  24. func addQueryStringSeg(body JSONObject, segs []sTextNumber, val []string) (JSONObject, error) {
  25. if len(segs) == 0 {
  26. if len(val) == 1 {
  27. return NewString(val[0]), nil
  28. } else if len(val) > 1 {
  29. return NewStringArray(val), nil
  30. }
  31. return nil, errors.Wrap(ErrNilInputField, "empty value???")
  32. }
  33. if body == nil {
  34. if segs[0].isNumber && segs[0].number == 0 {
  35. body = NewArray()
  36. } else {
  37. body = NewDict()
  38. }
  39. }
  40. switch jbody := body.(type) {
  41. case *JSONDict:
  42. key := segs[0].String()
  43. if !jbody.Contains(key) {
  44. next, err := addQueryStringSeg(nil, segs[1:], val)
  45. if err != nil {
  46. return nil, errors.Wrapf(err, "addQueryStringSeg %s with %s fail", body, key)
  47. }
  48. jbody.Add(next, key)
  49. } else {
  50. next, err := jbody.Get(key)
  51. if err != nil {
  52. return nil, errors.Wrapf(err, "get jsondict %s with %s fail", body, key)
  53. }
  54. addQueryStringSeg(next, segs[1:], val)
  55. }
  56. return jbody, nil
  57. case *JSONArray:
  58. index := segs[0].number
  59. arrSize := int64(jbody.Size())
  60. if index < arrSize {
  61. next, err := jbody.GetAt(int(index))
  62. if err != nil {
  63. return nil, errors.Wrapf(err, "get jsonarray %s at %d fail", body, index)
  64. }
  65. addQueryStringSeg(next, segs[1:], val)
  66. } else if arrSize == index {
  67. // new
  68. next, err := addQueryStringSeg(nil, segs[1:], val)
  69. if err != nil {
  70. return nil, errors.Wrapf(err, "addQueryStringSeg %s at %d fail", body, index)
  71. }
  72. jbody.Add(next)
  73. } else {
  74. return nil, errors.Wrapf(ErrOutOfIndexRange, "index %d out of range", index)
  75. }
  76. return jbody, nil
  77. default:
  78. return nil, errors.Wrapf(ErrTypeMismatch, "invalid body %s and key %s", body, segs)
  79. }
  80. }
  81. func (this *JSONDict) parseQueryString(str string) error {
  82. m, err := url.ParseQuery(str)
  83. if err != nil {
  84. return errors.Wrap(err, "url.ParseQuery")
  85. }
  86. keys := make([]string, 0)
  87. for k := range m {
  88. keys = append(keys, k)
  89. }
  90. segmentKeys := strings2stringSegments(keys)
  91. sort.Sort(segmentKeys)
  92. for _, segs := range segmentKeys {
  93. _, err := addQueryStringSeg(this, segs, m[segments2string(segs)])
  94. if err != nil {
  95. return errors.Wrap(err, "addQueryStringSeg")
  96. }
  97. }
  98. return nil
  99. }
  100. func ParseQueryString(str string) (JSONObject, error) {
  101. dict := NewDict()
  102. err := dict.parseQueryString(str)
  103. if err != nil {
  104. return nil, errors.Wrap(err, "dict.parseQueryString")
  105. }
  106. return dict, nil
  107. }
  108. func simpleQueryString(key, val string) string {
  109. if len(key) > 0 && len(val) > 0 {
  110. return url.QueryEscape(key) + "=" + url.QueryEscape(val)
  111. } else if len(val) > 0 {
  112. return url.QueryEscape(val)
  113. } else if len(key) > 0 {
  114. return url.QueryEscape(key)
  115. } else {
  116. return ""
  117. }
  118. }
  119. func (this *JSONValue) _queryString(key string) string {
  120. return simpleQueryString(key, "")
  121. }
  122. func (this *JSONString) _queryString(key string) string {
  123. return simpleQueryString(key, this.data)
  124. }
  125. func (this *JSONInt) _queryString(key string) string {
  126. return simpleQueryString(key, this.String())
  127. }
  128. func (this *JSONFloat) _queryString(key string) string {
  129. return simpleQueryString(key, this.String())
  130. }
  131. func (this *JSONBool) _queryString(key string) string {
  132. return simpleQueryString(key, this.String())
  133. }
  134. func (this *JSONArray) _queryString(key string) string {
  135. rets := make([]string, 0)
  136. for i, val := range this.data {
  137. k := strconv.FormatInt(int64(i), 10)
  138. if len(key) > 0 {
  139. k = key + "." + k
  140. }
  141. rets = append(rets, val._queryString(k))
  142. }
  143. return strings.Join(rets, "&")
  144. }
  145. func (this *JSONDict) _queryString(key string) string {
  146. rets := make([]string, 0)
  147. for iter := sortedmap.NewIterator(this.data); iter.HasMore(); iter.Next() {
  148. k, vinf := iter.Get()
  149. v := vinf.(JSONObject)
  150. if len(key) > 0 {
  151. k = key + "." + k
  152. }
  153. rets = append(rets, v._queryString(k))
  154. }
  155. return strings.Join(rets, "&")
  156. }
  157. func (this *JSONValue) QueryString() string {
  158. return this._queryString("")
  159. }
  160. func (this *JSONDict) QueryString() string {
  161. return this._queryString("")
  162. }
  163. func QueryBoolean(query JSONObject, key string, defVal bool) bool {
  164. if query == nil {
  165. return defVal
  166. }
  167. jsonVal, _ := query.Get(key)
  168. if jsonVal != nil {
  169. str, _ := jsonVal.GetString()
  170. return utils.ToBool(str)
  171. } else {
  172. return defVal
  173. }
  174. }