client.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package http
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. smithy "github.com/aws/smithy-go"
  7. "github.com/aws/smithy-go/metrics"
  8. "github.com/aws/smithy-go/middleware"
  9. "github.com/aws/smithy-go/tracing"
  10. )
  11. // ClientDo provides the interface for custom HTTP client implementations.
  12. type ClientDo interface {
  13. Do(*http.Request) (*http.Response, error)
  14. }
  15. // ClientDoFunc provides a helper to wrap a function as an HTTP client for
  16. // round tripping requests.
  17. type ClientDoFunc func(*http.Request) (*http.Response, error)
  18. // Do will invoke the underlying func, returning the result.
  19. func (fn ClientDoFunc) Do(r *http.Request) (*http.Response, error) {
  20. return fn(r)
  21. }
  22. // ClientHandler wraps a client that implements the HTTP Do method. Standard
  23. // implementation is http.Client.
  24. type ClientHandler struct {
  25. client ClientDo
  26. Meter metrics.Meter // For HTTP client metrics.
  27. }
  28. // NewClientHandler returns an initialized middleware handler for the client.
  29. //
  30. // Deprecated: Use [NewClientHandlerWithOptions].
  31. func NewClientHandler(client ClientDo) ClientHandler {
  32. return NewClientHandlerWithOptions(client)
  33. }
  34. // NewClientHandlerWithOptions returns an initialized middleware handler for the client
  35. // with applied options.
  36. func NewClientHandlerWithOptions(client ClientDo, opts ...func(*ClientHandler)) ClientHandler {
  37. h := ClientHandler{
  38. client: client,
  39. }
  40. for _, opt := range opts {
  41. opt(&h)
  42. }
  43. if h.Meter == nil {
  44. h.Meter = metrics.NopMeterProvider{}.Meter("")
  45. }
  46. return h
  47. }
  48. // Handle implements the middleware Handler interface, that will invoke the
  49. // underlying HTTP client. Requires the input to be a Smithy *Request. Returns
  50. // a smithy *Response, or error if the request failed.
  51. func (c ClientHandler) Handle(ctx context.Context, input interface{}) (
  52. out interface{}, metadata middleware.Metadata, err error,
  53. ) {
  54. ctx, span := tracing.StartSpan(ctx, "DoHTTPRequest")
  55. defer span.End()
  56. ctx, client, err := withMetrics(ctx, c.client, c.Meter)
  57. if err != nil {
  58. return nil, metadata, fmt.Errorf("instrument with HTTP metrics: %w", err)
  59. }
  60. req, ok := input.(*Request)
  61. if !ok {
  62. return nil, metadata, fmt.Errorf("expect Smithy http.Request value as input, got unsupported type %T", input)
  63. }
  64. builtRequest := req.Build(ctx)
  65. if err := ValidateEndpointHost(builtRequest.Host); err != nil {
  66. return nil, metadata, err
  67. }
  68. span.SetProperty("http.method", req.Method)
  69. span.SetProperty("http.request_content_length", -1) // at least indicate unknown
  70. length, ok, err := req.StreamLength()
  71. if err != nil {
  72. return nil, metadata, err
  73. }
  74. if ok {
  75. span.SetProperty("http.request_content_length", length)
  76. }
  77. resp, err := client.Do(builtRequest)
  78. if resp == nil {
  79. // Ensure a http response value is always present to prevent unexpected
  80. // panics.
  81. resp = &http.Response{
  82. Header: http.Header{},
  83. Body: http.NoBody,
  84. }
  85. }
  86. if err != nil {
  87. err = &RequestSendError{Err: err}
  88. // Override the error with a context canceled error, if that was canceled.
  89. select {
  90. case <-ctx.Done():
  91. err = &smithy.CanceledError{Err: ctx.Err()}
  92. default:
  93. }
  94. }
  95. // HTTP RoundTripper *should* close the request body. But this may not happen in a timely manner.
  96. // So instead Smithy *Request Build wraps the body to be sent in a safe closer that will clear the
  97. // stream reference so that it can be safely reused.
  98. if builtRequest.Body != nil {
  99. _ = builtRequest.Body.Close()
  100. }
  101. span.SetProperty("net.protocol.version", fmt.Sprintf("%d.%d", resp.ProtoMajor, resp.ProtoMinor))
  102. span.SetProperty("http.status_code", resp.StatusCode)
  103. span.SetProperty("http.response_content_length", resp.ContentLength)
  104. return &Response{Response: resp}, metadata, err
  105. }
  106. // RequestSendError provides a generic request transport error. This error
  107. // should wrap errors making HTTP client requests.
  108. //
  109. // The ClientHandler will wrap the HTTP client's error if the client request
  110. // fails, and did not fail because of context canceled.
  111. type RequestSendError struct {
  112. Err error
  113. }
  114. // ConnectionError returns that the error is related to not being able to send
  115. // the request, or receive a response from the service.
  116. func (e *RequestSendError) ConnectionError() bool {
  117. return true
  118. }
  119. // Unwrap returns the underlying error, if there was one.
  120. func (e *RequestSendError) Unwrap() error {
  121. return e.Err
  122. }
  123. func (e *RequestSendError) Error() string {
  124. return fmt.Sprintf("request send failed, %v", e.Err)
  125. }
  126. // NopClient provides a client that ignores the request, and returns an empty
  127. // successful HTTP response value.
  128. type NopClient struct{}
  129. // Do ignores the request and returns a 200 status empty response.
  130. func (NopClient) Do(r *http.Request) (*http.Response, error) {
  131. return &http.Response{
  132. StatusCode: 200,
  133. Header: http.Header{},
  134. Body: http.NoBody,
  135. }, nil
  136. }