util.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. if opt.basicAuth.enabled {
  53. req.SetBasicAuth(opt.basicAuth.username, opt.basicAuth.password)
  54. }
  55. //tcp-too-many-open-files-debug
  56. req.Close = true
  57. resp, err := defaultClient.Do(req)
  58. if err != nil {
  59. err = errors.Wrapf(err, "do request [%s %s] err", method, url)
  60. if opt.dialog != nil {
  61. opt.dialog.AppendResponse(&trace.Response{
  62. Body: err.Error(),
  63. CostSeconds: time.Since(ts).Seconds(),
  64. })
  65. }
  66. if opt.logger != nil {
  67. opt.logger.Warn("doHTTP got err", zap.Error(err))
  68. }
  69. return nil, _StatusDoReqErr, err
  70. }
  71. defer resp.Body.Close()
  72. body, err := ioutil.ReadAll(resp.Body)
  73. if err != nil {
  74. err = errors.Wrapf(err, "read resp body from [%s %s] err", method, url)
  75. if opt.dialog != nil {
  76. opt.dialog.AppendResponse(&trace.Response{
  77. Body: err.Error(),
  78. CostSeconds: time.Since(ts).Seconds(),
  79. })
  80. }
  81. if opt.logger != nil {
  82. opt.logger.Warn("doHTTP got err", zap.Error(err))
  83. }
  84. return nil, _StatusReadRespErr, err
  85. }
  86. defer func() {
  87. if opt.dialog != nil {
  88. opt.dialog.AppendResponse(&trace.Response{
  89. Header: resp.Header,
  90. HttpCode: resp.StatusCode,
  91. HttpCodeMsg: resp.Status,
  92. Body: string(body), // unsafe
  93. CostSeconds: time.Since(ts).Seconds(),
  94. })
  95. }
  96. }()
  97. if resp.StatusCode != http.StatusOK {
  98. return nil, resp.StatusCode, newReplyErr(
  99. resp.StatusCode,
  100. body,
  101. errors.Errorf("do [%s %s] return code: %d message: %s", method, url, resp.StatusCode, string(body)),
  102. )
  103. }
  104. return body, http.StatusOK, nil
  105. }
  106. // addFormValuesIntoURL append url.Values into url string
  107. func addFormValuesIntoURL(rawURL string, form url.Values) (string, error) {
  108. if rawURL == "" {
  109. return "", errors.New("rawURL required")
  110. }
  111. if len(form) == 0 {
  112. return "", errors.New("form required")
  113. }
  114. target, err := url.Parse(rawURL)
  115. if err != nil {
  116. return "", errors.Wrapf(err, "parse rawURL `%s` err", rawURL)
  117. }
  118. urlValues := target.Query()
  119. for key, values := range form {
  120. for _, value := range values {
  121. urlValues.Add(key, value)
  122. }
  123. }
  124. target.RawQuery = urlValues.Encode()
  125. return target.String(), nil
  126. }