util.go 3.4 KB

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