util.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package httpclient
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "git.bvbej.com/bvbej/base-golang/pkg/trace"
  11. "github.com/pkg/errors"
  12. "go.uber.org/zap"
  13. )
  14. const (
  15. // _StatusReadRespErr read resp body err, should re-call doHTTP again.
  16. _StatusReadRespErr = -204
  17. // _StatusDoReqErr do req err, should re-call doHTTP again.
  18. _StatusDoReqErr = -500
  19. )
  20. var defaultClient = &http.Client{
  21. Transport: &http.Transport{
  22. DisableKeepAlives: true,
  23. DisableCompression: true,
  24. TLSClientConfig: &tls.Config{
  25. InsecureSkipVerify: true,
  26. },
  27. MaxIdleConns: 100,
  28. MaxConnsPerHost: 100,
  29. MaxIdleConnsPerHost: 100,
  30. },
  31. }
  32. func doHTTP(ctx context.Context, method, url string, payload []byte, opt *option) ([]byte, int, error) {
  33. ts := time.Now()
  34. if mock := opt.mock; mock != nil {
  35. if opt.dialog != nil {
  36. opt.dialog.AppendResponse(&trace.Response{
  37. HttpCode: http.StatusOK,
  38. HttpCodeMsg: http.StatusText(http.StatusOK),
  39. Body: string(mock()),
  40. CostSeconds: time.Since(ts).Seconds(),
  41. })
  42. }
  43. return mock(), http.StatusOK, nil
  44. }
  45. req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(payload))
  46. if err != nil {
  47. return nil, -1, errors.Wrapf(err, "new request [%s %s] err", method, url)
  48. }
  49. for key, value := range opt.header {
  50. req.Header.Set(key, value[0])
  51. }
  52. resp, err := defaultClient.Do(req)
  53. if err != nil {
  54. err = errors.Wrapf(err, "do request [%s %s] err", method, url)
  55. if opt.dialog != nil {
  56. opt.dialog.AppendResponse(&trace.Response{
  57. Body: err.Error(),
  58. CostSeconds: time.Since(ts).Seconds(),
  59. })
  60. }
  61. if opt.logger != nil {
  62. opt.logger.Warn("doHTTP got err", zap.Error(err))
  63. }
  64. return nil, _StatusDoReqErr, err
  65. }
  66. defer resp.Body.Close()
  67. body, err := ioutil.ReadAll(resp.Body)
  68. if err != nil {
  69. err = errors.Wrapf(err, "read resp body from [%s %s] err", method, url)
  70. if opt.dialog != nil {
  71. opt.dialog.AppendResponse(&trace.Response{
  72. Body: err.Error(),
  73. CostSeconds: time.Since(ts).Seconds(),
  74. })
  75. }
  76. if opt.logger != nil {
  77. opt.logger.Warn("doHTTP got err", zap.Error(err))
  78. }
  79. return nil, _StatusReadRespErr, err
  80. }
  81. defer func() {
  82. if opt.dialog != nil {
  83. opt.dialog.AppendResponse(&trace.Response{
  84. Header: resp.Header,
  85. HttpCode: resp.StatusCode,
  86. HttpCodeMsg: resp.Status,
  87. Body: string(body), // unsafe
  88. CostSeconds: time.Since(ts).Seconds(),
  89. })
  90. }
  91. }()
  92. if resp.StatusCode != http.StatusOK {
  93. return nil, resp.StatusCode, newReplyErr(
  94. resp.StatusCode,
  95. body,
  96. errors.Errorf("do [%s %s] return code: %d message: %s", method, url, resp.StatusCode, string(body)),
  97. )
  98. }
  99. return body, http.StatusOK, nil
  100. }
  101. // addFormValuesIntoURL append url.Values into url string
  102. func addFormValuesIntoURL(rawURL string, form url.Values) (string, error) {
  103. if rawURL == "" {
  104. return "", errors.New("rawURL required")
  105. }
  106. if len(form) == 0 {
  107. return "", errors.New("form required")
  108. }
  109. target, err := url.Parse(rawURL)
  110. if err != nil {
  111. return "", errors.Wrapf(err, "parse rawURL `%s` err", rawURL)
  112. }
  113. urlValues := target.Query()
  114. for key, values := range form {
  115. for _, value := range values {
  116. urlValues.Add(key, value)
  117. }
  118. }
  119. target.RawQuery = urlValues.Encode()
  120. return target.String(), nil
  121. }