middleware_min_proto.go raw

   1  package http
   2  
   3  import (
   4  	"context"
   5  	"fmt"
   6  	"github.com/aws/smithy-go/middleware"
   7  	"strings"
   8  )
   9  
  10  // MinimumProtocolError is an error type indicating that the established connection did not meet the expected minimum
  11  // HTTP protocol version.
  12  type MinimumProtocolError struct {
  13  	proto              string
  14  	expectedProtoMajor int
  15  	expectedProtoMinor int
  16  }
  17  
  18  // Error returns the error message.
  19  func (m *MinimumProtocolError) Error() string {
  20  	return fmt.Sprintf("operation requires minimum HTTP protocol of HTTP/%d.%d, but was %s",
  21  		m.expectedProtoMajor, m.expectedProtoMinor, m.proto)
  22  }
  23  
  24  // RequireMinimumProtocol is a deserialization middleware that asserts that the established HTTP connection
  25  // meets the minimum major ad minor version.
  26  type RequireMinimumProtocol struct {
  27  	ProtoMajor int
  28  	ProtoMinor int
  29  }
  30  
  31  // AddRequireMinimumProtocol adds the RequireMinimumProtocol middleware to the stack using the provided minimum
  32  // protocol major and minor version.
  33  func AddRequireMinimumProtocol(stack *middleware.Stack, major, minor int) error {
  34  	return stack.Deserialize.Insert(&RequireMinimumProtocol{
  35  		ProtoMajor: major,
  36  		ProtoMinor: minor,
  37  	}, "OperationDeserializer", middleware.Before)
  38  }
  39  
  40  // ID returns the middleware identifier string.
  41  func (r *RequireMinimumProtocol) ID() string {
  42  	return "RequireMinimumProtocol"
  43  }
  44  
  45  // HandleDeserialize asserts that the established connection is a HTTP connection with the minimum major and minor
  46  // protocol version.
  47  func (r *RequireMinimumProtocol) HandleDeserialize(
  48  	ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler,
  49  ) (
  50  	out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
  51  ) {
  52  	out, metadata, err = next.HandleDeserialize(ctx, in)
  53  	if err != nil {
  54  		return out, metadata, err
  55  	}
  56  
  57  	response, ok := out.RawResponse.(*Response)
  58  	if !ok {
  59  		return out, metadata, fmt.Errorf("unknown transport type: %T", out.RawResponse)
  60  	}
  61  
  62  	if !strings.HasPrefix(response.Proto, "HTTP") {
  63  		return out, metadata, &MinimumProtocolError{
  64  			proto:              response.Proto,
  65  			expectedProtoMajor: r.ProtoMajor,
  66  			expectedProtoMinor: r.ProtoMinor,
  67  		}
  68  	}
  69  
  70  	if response.ProtoMajor < r.ProtoMajor || response.ProtoMinor < r.ProtoMinor {
  71  		return out, metadata, &MinimumProtocolError{
  72  			proto:              response.Proto,
  73  			expectedProtoMajor: r.ProtoMajor,
  74  			expectedProtoMinor: r.ProtoMinor,
  75  		}
  76  	}
  77  
  78  	return out, metadata, err
  79  }
  80