ghttp_func.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 ghttp
  7. import (
  8. "github.com/gogf/gf/errors/gerror"
  9. "github.com/gogf/gf/text/gstr"
  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. // niceCallFunc calls function <f> with exception capture logic.
  64. func niceCallFunc(f func()) {
  65. defer func() {
  66. if exception := recover(); exception != nil {
  67. switch exception {
  68. case exceptionExit, exceptionExitAll:
  69. return
  70. default:
  71. if _, ok := exception.(errorStack); ok {
  72. // It's already an error that has stack info.
  73. panic(exception)
  74. } else {
  75. // Create a new error with stack info.
  76. // Note that there's a skip pointing the start stacktrace
  77. // of the real error point.
  78. if err, ok := exception.(error); ok {
  79. panic(gerror.Wrap(err, ""))
  80. } else {
  81. panic(gerror.NewSkipf(1, "%v", exception))
  82. }
  83. }
  84. }
  85. }
  86. }()
  87. f()
  88. }