httputils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package httputil provides HTTP functions for internal usage only.
  7. package httputil
  8. import (
  9. "net/http"
  10. "strings"
  11. "github.com/gogf/gf/v2/encoding/gurl"
  12. "github.com/gogf/gf/v2/text/gstr"
  13. "github.com/gogf/gf/v2/util/gconv"
  14. )
  15. const (
  16. fileUploadingKey = "@file:"
  17. )
  18. // BuildParams builds the request string for the http client. The `params` can be type of:
  19. // string/[]byte/map/struct/*struct.
  20. //
  21. // The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data.
  22. func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
  23. // If given string/[]byte, converts and returns it directly as string.
  24. switch v := params.(type) {
  25. case string, []byte:
  26. return gconv.String(params)
  27. case []interface{}:
  28. if len(v) > 0 {
  29. params = v[0]
  30. } else {
  31. params = nil
  32. }
  33. }
  34. // Else converts it to map and does the url encoding.
  35. m, urlEncode := gconv.Map(params), true
  36. if len(m) == 0 {
  37. return gconv.String(params)
  38. }
  39. if len(noUrlEncode) == 1 {
  40. urlEncode = !noUrlEncode[0]
  41. }
  42. // If there's file uploading, it ignores the url encoding.
  43. if urlEncode {
  44. for k, v := range m {
  45. if gstr.Contains(k, fileUploadingKey) || gstr.Contains(gconv.String(v), fileUploadingKey) {
  46. urlEncode = false
  47. break
  48. }
  49. }
  50. }
  51. s := ""
  52. for k, v := range m {
  53. if len(encodedParamStr) > 0 {
  54. encodedParamStr += "&"
  55. }
  56. s = gconv.String(v)
  57. if urlEncode && len(s) > 6 && strings.Compare(s[0:6], fileUploadingKey) != 0 {
  58. s = gurl.Encode(s)
  59. }
  60. encodedParamStr += k + "=" + s
  61. }
  62. return
  63. }
  64. // HeaderToMap coverts request headers to map.
  65. func HeaderToMap(header http.Header) map[string]interface{} {
  66. m := make(map[string]interface{})
  67. for k, v := range header {
  68. if len(v) > 1 {
  69. m[k] = v
  70. } else {
  71. m[k] = v[0]
  72. }
  73. }
  74. return m
  75. }