httputils.go 1.9 KB

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