httputils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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/internal/empty"
  13. "github.com/gogf/gf/v2/text/gstr"
  14. "github.com/gogf/gf/v2/util/gconv"
  15. )
  16. const (
  17. fileUploadingKey = "@file:"
  18. )
  19. // BuildParams builds the request string for the http client. The `params` can be type of:
  20. // string/[]byte/map/struct/*struct.
  21. //
  22. // The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data.
  23. func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
  24. // If given string/[]byte, converts and returns it directly as string.
  25. switch v := params.(type) {
  26. case string, []byte:
  27. return gconv.String(params)
  28. case []interface{}:
  29. if len(v) > 0 {
  30. params = v[0]
  31. } else {
  32. params = nil
  33. }
  34. }
  35. // Else converts it to map and does the url encoding.
  36. m, urlEncode := gconv.Map(params), true
  37. if len(m) == 0 {
  38. return gconv.String(params)
  39. }
  40. if len(noUrlEncode) == 1 {
  41. urlEncode = !noUrlEncode[0]
  42. }
  43. // If there's file uploading, it ignores the url encoding.
  44. if urlEncode {
  45. for k, v := range m {
  46. if gstr.Contains(k, fileUploadingKey) || gstr.Contains(gconv.String(v), fileUploadingKey) {
  47. urlEncode = false
  48. break
  49. }
  50. }
  51. }
  52. s := ""
  53. for k, v := range m {
  54. // Ignore nil attributes.
  55. if empty.IsNil(v) {
  56. continue
  57. }
  58. if len(encodedParamStr) > 0 {
  59. encodedParamStr += "&"
  60. }
  61. s = gconv.String(v)
  62. if urlEncode {
  63. if strings.HasPrefix(s, fileUploadingKey) && len(s) > len(fileUploadingKey) {
  64. // No url encoding if uploading file.
  65. } else {
  66. s = gurl.Encode(s)
  67. }
  68. }
  69. encodedParamStr += k + "=" + s
  70. }
  71. return
  72. }
  73. // HeaderToMap coverts request headers to map.
  74. func HeaderToMap(header http.Header) map[string]interface{} {
  75. m := make(map[string]interface{})
  76. for k, v := range header {
  77. if len(v) > 1 {
  78. m[k] = v
  79. } else if len(v) == 1 {
  80. m[k] = v[0]
  81. }
  82. }
  83. return m
  84. }