go_retry.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package client
  2. import (
  3. "context"
  4. "git.finogeeks.club/base/apm"
  5. "net"
  6. "net/http"
  7. "time"
  8. "github.com/go-resty/resty/v2"
  9. )
  10. var restyClient = resty.NewWithClient(&http.Client{
  11. Transport: createTransport(nil),
  12. })
  13. func Request(ctx context.Context) *resty.Request {
  14. return restyClient.R().SetContext(ctx)
  15. }
  16. func createTransport(localAddr net.Addr) http.RoundTripper {
  17. dialer := &net.Dialer{
  18. Timeout: 30 * time.Second,
  19. KeepAlive: 30 * time.Second,
  20. }
  21. if localAddr != nil {
  22. dialer.LocalAddr = localAddr
  23. }
  24. return &apmRetryTransport{&http.Transport{
  25. Proxy: http.ProxyFromEnvironment,
  26. DialContext: dialer.DialContext,
  27. MaxIdleConns: 200,
  28. IdleConnTimeout: 90 * time.Second,
  29. TLSHandshakeTimeout: 10 * time.Second,
  30. ExpectContinueTimeout: 1 * time.Second,
  31. MaxIdleConnsPerHost: 200,
  32. }}
  33. }
  34. type apmRetryTransport struct {
  35. *http.Transport
  36. }
  37. func (transport *apmRetryTransport) RoundTrip(request *http.Request) (*http.Response, error) {
  38. eSpan := apm.ApmClient().CreateHttpExitSpan(request.Context(), request, request.URL.Host, request.URL.Path)
  39. defer eSpan.End()
  40. resp, err := transport.Transport.RoundTrip(request)
  41. return resp, err
  42. }