chore: upgrade dependencies

This commit is contained in:
2022-06-09 12:30:53 +02:00
parent 7203f3d6a1
commit dcb93ec8f7
518 changed files with 27809 additions and 3222 deletions

View File

@@ -1,3 +1,37 @@
# Release (v1.11.3)
## Module Highlights
* `github.com/aws/smithy-go`: v1.11.3
* **Dependency Update**: Updates smithy-go unit test dependency go-cmp to 0.5.8.
# Release (v1.11.2)
* No change notes available for this release.
# Release (v1.11.1)
## Module Highlights
* `github.com/aws/smithy-go`: v1.11.1
* **Bug Fix**: Updates the smithy-go HTTP Request to correctly handle building the request to an http.Request. Related to [aws/aws-sdk-go-v2#1583](https://github.com/aws/aws-sdk-go-v2/issues/1583)
# Release (v1.11.0)
## Module Highlights
* `github.com/aws/smithy-go`: v1.11.0
* **Feature**: Updates deserialization of header list to supported quoted strings
# Release (v1.10.0)
## Module Highlights
* `github.com/aws/smithy-go`: v1.10.0
* **Feature**: Add `ptr.Duration`, `ptr.ToDuration`, `ptr.DurationSlice`, `ptr.ToDurationSlice`, `ptr.DurationMap`, and `ptr.ToDurationMap` functions for the `time.Duration` type.
# Release (v1.9.1)
## Module Highlights
* `github.com/aws/smithy-go`: v1.9.1
* **Documentation**: Fixes various typos in Go package documentation.
# Release (v1.9.0)
## Module Highlights

View File

@@ -1,3 +1,4 @@
PRE_RELEASE_VERSION ?=
RELEASE_MANIFEST_FILE ?=
RELEASE_CHGLOG_DESC_FILE ?=
@@ -5,6 +6,7 @@ RELEASE_CHGLOG_DESC_FILE ?=
REPOTOOLS_VERSION ?= latest
REPOTOOLS_MODULE = github.com/awslabs/aws-go-multi-module-repository-tools
REPOTOOLS_CMD_CALCULATE_RELEASE = ${REPOTOOLS_MODULE}/cmd/calculaterelease@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS ?=
REPOTOOLS_CMD_UPDATE_REQUIRES = ${REPOTOOLS_MODULE}/cmd/updaterequires@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_UPDATE_MODULE_METADATA = ${REPOTOOLS_MODULE}/cmd/updatemodulemeta@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_GENERATE_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/generatechangelog@${REPOTOOLS_VERSION}
@@ -12,6 +14,10 @@ REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION}
REPOTOOLS_CMD_MODULE_VERSION = ${REPOTOOLS_MODULE}/cmd/moduleversion@${REPOTOOLS_VERSION}
ifneq ($(PRE_RELEASE_VERSION),)
REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS += -preview=${PRE_RELEASE_VERSION}
endif
smithy-publish-local:
cd codegen && ./gradlew publishToMavenLocal
@@ -27,7 +33,7 @@ smithy-clean:
.PHONY: preview-release pre-release-validation release
preview-release:
go run ${REPOTOOLS_CMD_CALCULATE_RELEASE}
go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS}
pre-release-validation:
@if [[ -z "${RELEASE_MANIFEST_FILE}" ]]; then \
@@ -38,7 +44,7 @@ pre-release-validation:
fi
release: pre-release-validation
go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} -o ${RELEASE_MANIFEST_FILE}
go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} -o ${RELEASE_MANIFEST_FILE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS}
go run ${REPOTOOLS_CMD_UPDATE_REQUIRES} -release ${RELEASE_MANIFEST_FILE}
go run ${REPOTOOLS_CMD_UPDATE_MODULE_METADATA} -release ${RELEASE_MANIFEST_FILE}
go run ${REPOTOOLS_CMD_GENERATE_CHANGELOG} -release ${RELEASE_MANIFEST_FILE} -o ${RELEASE_CHGLOG_DESC_FILE}

View File

@@ -36,7 +36,7 @@ import (
// - document field tag is "-"
// - document field tag specifies "omitempty", and is a zero value.
//
// Pointer and interfaces values are encoded as the value pointed to or
// Pointer and interface values are encoded as the value pointed to or
// contained in the interface. A nil value encodes as a null
// value unless `omitempty` struct tag is provided.
//
@@ -46,7 +46,7 @@ import (
// time.Time is not supported and will cause the Marshaler to return an error. These values should be represented
// by your application as a string or numerical representation.
//
// Errors that occur when marshaling will stop the marshaller, and return the error.
// Errors that occur when marshaling will stop the marshaler, and return the error.
//
// Marshal cannot represent cyclic data structures and will not handle them.
// Passing cyclic structures to Marshal will result in an infinite recursion.
@@ -54,14 +54,14 @@ type Marshaler interface {
MarshalSmithyDocument() ([]byte, error)
}
// Unmarshaler is an interface for a type that unmarshalls a document from its protocol-specific representation, and
// Unmarshaler is an interface for a type that unmarshals a document from its protocol-specific representation, and
// stores the result into the value pointed by v. If v is nil or not a pointer then InvalidUnmarshalError will be
// returned.
//
// Unmarshaler supports the same encodings produced by a document Marshaler. This includes support for the `document`
// struct field tag for controlling how struct fields are unmarshalled.
// struct field tag for controlling how struct fields are unmarshaled.
//
// Both generic interface{} and concrete types are valid unmarshal destination types. When unmarshalling a document
// Both generic interface{} and concrete types are valid unmarshal destination types. When unmarshaling a document
// into an empty interface the Unmarshaler will store one of these values:
// bool, for boolean values
// document.Number, for arbitrary-precision numbers (int64, float64, big.Int, big.Float)
@@ -70,7 +70,7 @@ type Marshaler interface {
// map[string]interface{}, for objects
// nil, for null values
//
// When unmarshalling, any error that occurs will halt the unmarshal and return the error.
// When unmarshaling, any error that occurs will halt the unmarshal and return the error.
type Unmarshaler interface {
UnmarshalSmithyDocument(v interface{}) error
}
@@ -79,7 +79,7 @@ type noSerde interface {
noSmithyDocumentSerde()
}
// NoSerde is a sentinel value to indicate that a given type should not be marshaled or unmarshalled
// NoSerde is a sentinel value to indicate that a given type should not be marshaled or unmarshaled
// into a protocol document.
type NoSerde struct{}
@@ -93,7 +93,7 @@ func IsNoSerde(x interface{}) bool {
return ok
}
// Number is a arbitrary precision numerical value
// Number is an arbitrary precision numerical value
type Number string
// Int64 returns the number as a string.
@@ -110,7 +110,7 @@ func (n Number) intOfBitSize(bitSize int) (int64, error) {
return strconv.ParseInt(string(n), 10, bitSize)
}
// Uint64 returns the number as an uint64.
// Uint64 returns the number as a uint64.
func (n Number) Uint64() (uint64, error) {
return n.uintOfBitSize(64)
}

View File

@@ -5,8 +5,8 @@ import (
"reflect"
)
// UnmarshalTypeError is an error type representing aa error
// unmarshalling a Smithy document to a Go value type. This is different
// UnmarshalTypeError is an error type representing an error
// unmarshaling a Smithy document to a Go value type. This is different
// from UnmarshalError in that it does not wrap an underlying error type.
type UnmarshalTypeError struct {
Value string
@@ -14,20 +14,20 @@ type UnmarshalTypeError struct {
}
// Error returns the string representation of the error.
// satisfying the error interface
// Satisfying the error interface.
func (e *UnmarshalTypeError) Error() string {
return fmt.Sprintf("unmarshal failed, cannot unmarshal %s into Go value type %s",
e.Value, e.Type.String())
}
// An InvalidUnmarshalError is an error type representing an invalid type
// encountered while unmarshalling a Smithy document to a Go value type.
// encountered while unmarshaling a Smithy document to a Go value type.
type InvalidUnmarshalError struct {
Type reflect.Type
}
// Error returns the string representation of the error.
// satisfying the error interface
// Satisfying the error interface.
func (e *InvalidUnmarshalError) Error() string {
var msg string
if e.Type == nil {
@@ -41,7 +41,7 @@ func (e *InvalidUnmarshalError) Error() string {
return fmt.Sprintf("unmarshal failed, %s", msg)
}
// An UnmarshalError wraps an error that occurred while unmarshalling a
// An UnmarshalError wraps an error that occurred while unmarshaling a
// Smithy document into a Go type. This is different from
// UnmarshalTypeError in that it wraps the underlying error that occurred.
type UnmarshalError struct {
@@ -50,13 +50,13 @@ type UnmarshalError struct {
Type reflect.Type
}
// Unwrap returns the underlying unmarshalling error
// Unwrap returns the underlying unmarshaling error
func (e *UnmarshalError) Unwrap() error {
return e.Err
}
// Error returns the string representation of the error satisfying the error
// interface.
// Error returns the string representation of the error.
// Satisfying the error interface.
func (e *UnmarshalError) Error() string {
return fmt.Sprintf("unmarshal failed, cannot unmarshal %q into %s, %v",
e.Value, e.Type.String(), e.Err)
@@ -69,7 +69,7 @@ type InvalidMarshalError struct {
}
// Error returns the string representation of the error.
// satisfying the error interface
// Satisfying the error interface.
func (e *InvalidMarshalError) Error() string {
return fmt.Sprintf("marshal failed, %s", e.Message)
}

View File

@@ -50,7 +50,7 @@ func NewEncoder(path, query string, headers http.Header) (*Encoder, error) {
// Due net/http requiring `Content-Length` to be specified on the http.Request#ContentLength directly. Encode
// will look for whether the header is present, and if so will remove it and set the respective value on http.Request.
//
// Returns any error if one occurred during encoding.
// Returns any error occurring during encoding.
func (e *Encoder) Encode(req *http.Request) (*http.Request, error) {
req.URL.Path, req.URL.RawPath = string(e.path), string(e.rawPath)
req.URL.RawQuery = e.query.Encode()
@@ -80,7 +80,7 @@ func (e *Encoder) SetHeader(key string) HeaderValue {
return newHeaderValue(e.header, key, false)
}
// Headers returns a Header used encoding headers with the given prefix
// Headers returns a Header used for encoding headers with the given prefix
func (e *Encoder) Headers(prefix string) Headers {
return Headers{
header: e.header,
@@ -110,7 +110,7 @@ func (e *Encoder) AddQuery(key string) QueryValue {
}
// HasQuery returns if a query with the key specified exists with one or
// more value.
// more values.
func (e *Encoder) HasQuery(key string) bool {
return len(e.query.Get(key)) != 0
}

View File

@@ -20,6 +20,9 @@ func newURIValue(path *[]byte, rawPath *[]byte, buffer *[]byte, key string) URIV
func (u URIValue) modifyURI(value string) (err error) {
*u.path, *u.buffer, err = replacePathElement(*u.path, *u.buffer, u.key, value, false)
if err != nil {
return err
}
*u.rawPath, *u.buffer, err = replacePathElement(*u.rawPath, *u.buffer, u.key, value, true)
return err
}

View File

@@ -4,7 +4,7 @@ import (
"bytes"
)
// Array represent the encoding of a JSON Array
// Array represents the encoding of a JSON Array
type Array struct {
w *bytes.Buffer
writeComma bool

View File

@@ -7,8 +7,8 @@ import (
"io"
)
// DiscardUnknownField discards unknown fields from decoder body.
// This function is useful while deserializing json body with additional
// DiscardUnknownField discards unknown fields from a decoder body.
// This function is useful while deserializing a JSON body with additional
// unknown information that should be discarded.
func DiscardUnknownField(decoder *json.Decoder) error {
// This deliberately does not share logic with CollectUnknownField, even

View File

@@ -60,7 +60,7 @@ func (e *OperationError) Error() string {
return fmt.Sprintf("operation error %s: %s, %v", e.ServiceID, e.OperationName, e.Err)
}
// DeserializationError provides a wrapper for and error that occurs during
// DeserializationError provides a wrapper for an error that occurs during
// deserialization.
type DeserializationError struct {
Err error // original error

View File

@@ -3,4 +3,4 @@
package smithy
// goModuleVersion is the tagged release for this module
const goModuleVersion = "1.9.0"
const goModuleVersion = "1.11.3"

View File

@@ -24,7 +24,7 @@ func NewRingBuffer(slice []byte) *RingBuffer {
return &ringBuf
}
// Write method inserts the elements in a byte slice, and returns the number of bytes written along with an error.
// Write method inserts the elements in a byte slice, and returns the number of bytes written along with any error.
func (r *RingBuffer) Write(p []byte) (int, error) {
for _, b := range p {
// check if end points to invalid index, we need to circle back
@@ -49,7 +49,7 @@ func (r *RingBuffer) Write(p []byte) (int, error) {
}
// Read copies the data on the ring buffer into the byte slice provided to the method.
// Returns the read count along with Error encountered while reading
// Returns the read count along with any error encountered while reading.
func (r *RingBuffer) Read(p []byte) (int, error) {
// readCount keeps track of the number of bytes read
var readCount int

View File

@@ -6,7 +6,7 @@ import (
"log"
)
// Classification the log entry's classification name
// Classification is the type of the log entry's classification name.
type Classification string
// Set of standard classifications that can be used by clients and middleware

View File

@@ -1,4 +1,4 @@
// Package middleware provide transport agnostic middleware for decorating SDK
// Package middleware provides transport agnostic middleware for decorating SDK
// handlers.
//
// The Smithy middleware stack provides ordered behavior to be invoked on an
@@ -24,7 +24,7 @@
// order by the Stack. These steps represent fixed points in the middleware stack
// for organizing specific behavior, such as serialize and build. A Stack Step is
// composed of zero or more middleware that are specific to that step. A step may
// define its on set of input/output parameters the generic input/output
// define its own set of input/output parameters the generic input/output
// parameters are cast from. A step calls its middleware recursively, before
// calling the next step in the stack returning the result or error of the step
// middleware decorating the underlying handler.
@@ -39,7 +39,7 @@
// HTTP's Content-Length header, or body checksum). Decorations and
// modifications to the message should be copied to all message attempts.
//
// * Finalize: Preforms final preparations needed before sending the message. The
// * Finalize: Performs final preparations needed before sending the message. The
// message should already be complete by this stage, and is only alternated to
// meet the expectations of the recipient, (e.g. Retry and AWS SigV4 request
// signing).
@@ -51,8 +51,8 @@
// Adding Middleware to a Stack Step
//
// Middleware can be added to a step front or back, or relative, by name, to an
// existing middleware in that stack. If a middleware does not have a name a
// unique name will be generated at the middleware is added to the step.
// existing middleware in that stack. If a middleware does not have a name, a
// unique name will be generated at the middleware and be added to the step.
//
// // Create middleware stack
// stack := middleware.NewStack()

View File

@@ -42,7 +42,7 @@ func (m Metadata) Clone() Metadata {
// that key it will be replaced with the new value.
//
// Set method must be called as an addressable value, or pointer. If Set is not
// called as a addressable value or pointer, the key value pair being set may
// called as an addressable value or pointer, the key value pair being set may
// be lost.
//
// Panics if the key type is not comparable.
@@ -53,7 +53,7 @@ func (m *Metadata) Set(key, value interface{}) {
m.values[key] = value
}
// Has returns if the key exists in the metadata.
// Has returns whether the key exists in the metadata.
//
// Panics if the key type is not comparable.
func (m Metadata) Has(key interface{}) bool {

View File

@@ -48,7 +48,7 @@ func (g *orderedIDs) Add(m ider, pos RelativePosition) error {
return nil
}
// Insert injects the item relative to an existing item id. Return error if
// Insert injects the item relative to an existing item id. Returns an error if
// the original item does not exist, or the item being added already exists.
func (g *orderedIDs) Insert(m ider, relativeTo string, pos RelativePosition) error {
if len(m.ID()) == 0 {
@@ -66,13 +66,13 @@ func (g *orderedIDs) Insert(m ider, relativeTo string, pos RelativePosition) err
return nil
}
// Get returns the ider identified by id. If ider is not present, returns false
// Get returns the ider identified by id. If ider is not present, returns false.
func (g *orderedIDs) Get(id string) (ider, bool) {
v, ok := g.items[id]
return v, ok
}
// Swap removes the item by id, replacing it with the new item. Returns error
// Swap removes the item by id, replacing it with the new item. Returns an error
// if the original item doesn't exist.
func (g *orderedIDs) Swap(id string, m ider) (ider, error) {
if len(id) == 0 {
@@ -96,7 +96,7 @@ func (g *orderedIDs) Swap(id string, m ider) (ider, error) {
return removed, nil
}
// Remove removes the item by id. Returns error if the item
// Remove removes the item by id. Returns an error if the item
// doesn't exist.
func (g *orderedIDs) Remove(id string) (ider, error) {
if len(id) == 0 {
@@ -147,7 +147,7 @@ func newRelativeOrder() *relativeOrder {
}
}
// Add inserts a item into the order relative to the position provided.
// Add inserts an item into the order relative to the position provided.
func (s *relativeOrder) Add(pos RelativePosition, ids ...string) error {
if len(ids) == 0 {
return nil
@@ -173,7 +173,7 @@ func (s *relativeOrder) Add(pos RelativePosition, ids ...string) error {
return nil
}
// Insert injects a item before or after the relative item. Returns
// Insert injects an item before or after the relative item. Returns
// an error if the relative item does not exist.
func (s *relativeOrder) Insert(relativeTo string, pos RelativePosition, ids ...string) error {
if len(ids) == 0 {
@@ -195,7 +195,7 @@ func (s *relativeOrder) Insert(relativeTo string, pos RelativePosition, ids ...s
}
// Swap will replace the item id with the to item. Returns an
// error if the original item id does not exist. Allows swapping out a
// error if the original item id does not exist. Allows swapping out an
// item for another item with the same id.
func (s *relativeOrder) Swap(id, to string) error {
i, ok := s.has(id)

View File

@@ -7,7 +7,7 @@ import (
)
// Stack provides protocol and transport agnostic set of middleware split into
// distinct steps. Steps have specific transitions between them, that is
// distinct steps. Steps have specific transitions between them, that are
// managed by the individual step.
//
// Steps are composed as middleware around the underlying handler in the
@@ -15,7 +15,7 @@ import (
//
// Initialize -> Serialize -> Build -> Finalize -> Deserialize -> Handler
//
// Any middleware within the chain may chose to stop and return an error or
// Any middleware within the chain may choose to stop and return an error or
// response. Since the middleware decorate the handler like a call stack, each
// middleware will receive the result of the next middleware in the chain.
// Middleware that does not need to react to an input, or result must forward
@@ -23,7 +23,7 @@ import (
//
// Initialize <- Serialize -> Build -> Finalize <- Deserialize <- Handler
type Stack struct {
// Initialize Prepares the input, and sets any default parameters as
// Initialize prepares the input, and sets any default parameters as
// needed, (e.g. idempotency token, and presigned URLs).
//
// Takes Input Parameters, and returns result or error.
@@ -31,7 +31,7 @@ type Stack struct {
// Receives result or error from Serialize step.
Initialize *InitializeStep
// Serializes the prepared input into a data structure that can be consumed
// Serialize serializes the prepared input into a data structure that can be consumed
// by the target transport's message, (e.g. REST-JSON serialization)
//
// Converts Input Parameters into a Request, and returns the result or error.
@@ -39,7 +39,7 @@ type Stack struct {
// Receives result or error from Build step.
Serialize *SerializeStep
// Adds additional metadata to the serialized transport message,
// Build adds additional metadata to the serialized transport message
// (e.g. HTTP's Content-Length header, or body checksum). Decorations and
// modifications to the message should be copied to all message attempts.
//
@@ -48,9 +48,9 @@ type Stack struct {
// Receives result or error from Finalize step.
Build *BuildStep
// Preforms final preparations needed before sending the message. The
// Finalize performs final preparations needed before sending the message. The
// message should already be complete by this stage, and is only alternated
// to meet the expectations of the recipient, (e.g. Retry and AWS SigV4
// to meet the expectations of the recipient (e.g. Retry and AWS SigV4
// request signing)
//
// Takes Request, and returns result or error.
@@ -58,7 +58,7 @@ type Stack struct {
// Receives result or error from Deserialize step.
Finalize *FinalizeStep
// Reacts to the handler's response returned by the recipient of the request
// Deserialize reacts to the handler's response returned by the recipient of the request
// message. Deserializes the response into a structured type or error above
// stacks can react to.
//

View File

@@ -6,7 +6,7 @@ import (
"strings"
)
// WithStackValue adds a key value pair to the context that are intended to be
// WithStackValue adds a key value pair to the context that is intended to be
// scoped to a stack. Use ClearStackValues to get a new context with all stack
// values cleared.
func WithStackValue(ctx context.Context, key, value interface{}) context.Context {

View File

@@ -70,12 +70,12 @@ func (s buildMiddlewareFunc) HandleBuild(ctx context.Context, in BuildInput, nex
var _ BuildMiddleware = (buildMiddlewareFunc{})
// BuildStep provides the ordered grouping of BuildMiddleware to be invoked on
// an handler.
// a handler.
type BuildStep struct {
ids *orderedIDs
}
// NewBuildStep returns an BuildStep ready to have middleware for
// NewBuildStep returns a BuildStep ready to have middleware for
// initialization added to it.
func NewBuildStep() *BuildStep {
return &BuildStep{
@@ -131,14 +131,14 @@ func (s *BuildStep) Add(m BuildMiddleware, pos RelativePosition) error {
}
// Insert injects the middleware relative to an existing middleware id.
// Return error if the original middleware does not exist, or the middleware
// Returns an error if the original middleware does not exist, or the middleware
// being added already exists.
func (s *BuildStep) Insert(m BuildMiddleware, relativeTo string, pos RelativePosition) error {
return s.ids.Insert(m, relativeTo, pos)
}
// Swap removes the middleware by id, replacing it with the new middleware.
// Returns the middleware removed, or error if the middleware to be removed
// Returns the middleware removed, or an error if the middleware to be removed
// doesn't exist.
func (s *BuildStep) Swap(id string, m BuildMiddleware) (BuildMiddleware, error) {
removed, err := s.ids.Swap(id, m)

View File

@@ -12,7 +12,7 @@ type DeserializeInput struct {
}
// DeserializeOutput provides the result returned by the next
// DeserializeHandler. The DeserializeMiddleware should deserailize the
// DeserializeHandler. The DeserializeMiddleware should deserialize the
// RawResponse into a Result that can be consumed by middleware higher up in
// the stack.
type DeserializeOutput struct {
@@ -32,11 +32,11 @@ type DeserializeHandler interface {
// serialize step. Delegates to the next DeserializeHandler for further
// processing.
type DeserializeMiddleware interface {
// Unique ID for the middleware in the DeserializeStep. The step does not
// ID returns a unique ID for the middleware in the DeserializeStep. The step does not
// allow duplicate IDs.
ID() string
// Invokes the middleware behavior which must delegate to the next handler
// HandleDeserialize invokes the middleware behavior which must delegate to the next handler
// for the middleware chain to continue. The method must return a result or
// error to its caller.
HandleDeserialize(ctx context.Context, in DeserializeInput, next DeserializeHandler) (
@@ -76,12 +76,12 @@ func (s deserializeMiddlewareFunc) HandleDeserialize(ctx context.Context, in Des
var _ DeserializeMiddleware = (deserializeMiddlewareFunc{})
// DeserializeStep provides the ordered grouping of DeserializeMiddleware to be
// invoked on an handler.
// invoked on a handler.
type DeserializeStep struct {
ids *orderedIDs
}
// NewDeserializeStep returns an DeserializeStep ready to have middleware for
// NewDeserializeStep returns a DeserializeStep ready to have middleware for
// initialization added to it.
func NewDeserializeStep() *DeserializeStep {
return &DeserializeStep{
@@ -91,7 +91,7 @@ func NewDeserializeStep() *DeserializeStep {
var _ Middleware = (*DeserializeStep)(nil)
// ID returns the unique id of the step as a middleware.
// ID returns the unique ID of the step as a middleware.
func (s *DeserializeStep) ID() string {
return "Deserialize stack step"
}
@@ -136,8 +136,8 @@ func (s *DeserializeStep) Add(m DeserializeMiddleware, pos RelativePosition) err
return s.ids.Add(m, pos)
}
// Insert injects the middleware relative to an existing middleware id.
// Return error if the original middleware does not exist, or the middleware
// Insert injects the middleware relative to an existing middleware ID.
// Returns error if the original middleware does not exist, or the middleware
// being added already exists.
func (s *DeserializeStep) Insert(m DeserializeMiddleware, relativeTo string, pos RelativePosition) error {
return s.ids.Insert(m, relativeTo, pos)
@@ -182,7 +182,7 @@ type deserializeWrapHandler struct {
var _ DeserializeHandler = (*deserializeWrapHandler)(nil)
// Implements DeserializeHandler, converts types and delegates to underlying
// HandleDeserialize implements DeserializeHandler, converts types and delegates to underlying
// generic handler.
func (w deserializeWrapHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) (
out DeserializeOutput, metadata Metadata, err error,

View File

@@ -26,11 +26,11 @@ type FinalizeHandler interface {
// serialize step. Delegates to the next FinalizeHandler for further
// processing.
type FinalizeMiddleware interface {
// Unique ID for the middleware in the FinalizeStep. The step does not
// ID returns a unique ID for the middleware in the FinalizeStep. The step does not
// allow duplicate IDs.
ID() string
// Invokes the middleware behavior which must delegate to the next handler
// HandleFinalize invokes the middleware behavior which must delegate to the next handler
// for the middleware chain to continue. The method must return a result or
// error to its caller.
HandleFinalize(ctx context.Context, in FinalizeInput, next FinalizeHandler) (
@@ -70,12 +70,12 @@ func (s finalizeMiddlewareFunc) HandleFinalize(ctx context.Context, in FinalizeI
var _ FinalizeMiddleware = (finalizeMiddlewareFunc{})
// FinalizeStep provides the ordered grouping of FinalizeMiddleware to be
// invoked on an handler.
// invoked on a handler.
type FinalizeStep struct {
ids *orderedIDs
}
// NewFinalizeStep returns an FinalizeStep ready to have middleware for
// NewFinalizeStep returns a FinalizeStep ready to have middleware for
// initialization added to it.
func NewFinalizeStep() *FinalizeStep {
return &FinalizeStep{
@@ -130,8 +130,8 @@ func (s *FinalizeStep) Add(m FinalizeMiddleware, pos RelativePosition) error {
return s.ids.Add(m, pos)
}
// Insert injects the middleware relative to an existing middleware id.
// Return error if the original middleware does not exist, or the middleware
// Insert injects the middleware relative to an existing middleware ID.
// Returns error if the original middleware does not exist, or the middleware
// being added already exists.
func (s *FinalizeStep) Insert(m FinalizeMiddleware, relativeTo string, pos RelativePosition) error {
return s.ids.Insert(m, relativeTo, pos)
@@ -176,7 +176,7 @@ type finalizeWrapHandler struct {
var _ FinalizeHandler = (*finalizeWrapHandler)(nil)
// Implements FinalizeHandler, converts types and delegates to underlying
// HandleFinalize implements FinalizeHandler, converts types and delegates to underlying
// generic handler.
func (w finalizeWrapHandler) HandleFinalize(ctx context.Context, in FinalizeInput) (
out FinalizeOutput, metadata Metadata, err error,

View File

@@ -26,11 +26,11 @@ type InitializeHandler interface {
// initialize step. Delegates to the next InitializeHandler for further
// processing.
type InitializeMiddleware interface {
// Unique ID for the middleware in the InitializeStep. The step does not
// ID returns a unique ID for the middleware in the InitializeStep. The step does not
// allow duplicate IDs.
ID() string
// Invokes the middleware behavior which must delegate to the next handler
// HandleInitialize invokes the middleware behavior which must delegate to the next handler
// for the middleware chain to continue. The method must return a result or
// error to its caller.
HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) (
@@ -70,7 +70,7 @@ func (s initializeMiddlewareFunc) HandleInitialize(ctx context.Context, in Initi
var _ InitializeMiddleware = (initializeMiddlewareFunc{})
// InitializeStep provides the ordered grouping of InitializeMiddleware to be
// invoked on an handler.
// invoked on a handler.
type InitializeStep struct {
ids *orderedIDs
}
@@ -85,7 +85,7 @@ func NewInitializeStep() *InitializeStep {
var _ Middleware = (*InitializeStep)(nil)
// ID returns the unique id of the step as a middleware.
// ID returns the unique ID of the step as a middleware.
func (s *InitializeStep) ID() string {
return "Initialize stack step"
}
@@ -130,8 +130,8 @@ func (s *InitializeStep) Add(m InitializeMiddleware, pos RelativePosition) error
return s.ids.Add(m, pos)
}
// Insert injects the middleware relative to an existing middleware id.
// Return error if the original middleware does not exist, or the middleware
// Insert injects the middleware relative to an existing middleware ID.
// Returns error if the original middleware does not exist, or the middleware
// being added already exists.
func (s *InitializeStep) Insert(m InitializeMiddleware, relativeTo string, pos RelativePosition) error {
return s.ids.Insert(m, relativeTo, pos)
@@ -176,7 +176,7 @@ type initializeWrapHandler struct {
var _ InitializeHandler = (*initializeWrapHandler)(nil)
// Implements InitializeHandler, converts types and delegates to underlying
// HandleInitialize implements InitializeHandler, converts types and delegates to underlying
// generic handler.
func (w initializeWrapHandler) HandleInitialize(ctx context.Context, in InitializeInput) (
out InitializeOutput, metadata Metadata, err error,

View File

@@ -29,11 +29,11 @@ type SerializeHandler interface {
// serialize step. Delegates to the next SerializeHandler for further
// processing.
type SerializeMiddleware interface {
// Unique ID for the middleware in the SerializeStep. The step does not
// ID returns a unique ID for the middleware in the SerializeStep. The step does not
// allow duplicate IDs.
ID() string
// Invokes the middleware behavior which must delegate to the next handler
// HandleSerialize invokes the middleware behavior which must delegate to the next handler
// for the middleware chain to continue. The method must return a result or
// error to its caller.
HandleSerialize(ctx context.Context, in SerializeInput, next SerializeHandler) (
@@ -73,13 +73,13 @@ func (s serializeMiddlewareFunc) HandleSerialize(ctx context.Context, in Seriali
var _ SerializeMiddleware = (serializeMiddlewareFunc{})
// SerializeStep provides the ordered grouping of SerializeMiddleware to be
// invoked on an handler.
// invoked on a handler.
type SerializeStep struct {
newRequest func() interface{}
ids *orderedIDs
}
// NewSerializeStep returns an SerializeStep ready to have middleware for
// NewSerializeStep returns a SerializeStep ready to have middleware for
// initialization added to it. The newRequest func parameter is used to
// initialize the transport specific request for the stack SerializeStep to
// serialize the input parameters into.
@@ -92,7 +92,7 @@ func NewSerializeStep(newRequest func() interface{}) *SerializeStep {
var _ Middleware = (*SerializeStep)(nil)
// ID returns the unique id of the step as a middleware.
// ID returns the unique ID of the step as a middleware.
func (s *SerializeStep) ID() string {
return "Serialize stack step"
}
@@ -138,8 +138,8 @@ func (s *SerializeStep) Add(m SerializeMiddleware, pos RelativePosition) error {
return s.ids.Add(m, pos)
}
// Insert injects the middleware relative to an existing middleware id.
// Return error if the original middleware does not exist, or the middleware
// Insert injects the middleware relative to an existing middleware ID.
// Returns error if the original middleware does not exist, or the middleware
// being added already exists.
func (s *SerializeStep) Insert(m SerializeMiddleware, relativeTo string, pos RelativePosition) error {
return s.ids.Insert(m, relativeTo, pos)

View File

@@ -564,3 +564,38 @@ func ToTimeMap(vs map[string]*time.Time) map[string]time.Time {
return ps
}
// ToDuration returns time.Duration value dereferenced if the passed
// in pointer was not nil. Returns a time.Duration zero value if the
// pointer was nil.
func ToDuration(p *time.Duration) (v time.Duration) {
if p == nil {
return v
}
return *p
}
// ToDurationSlice returns a slice of time.Duration values, that are
// dereferenced if the passed in pointer was not nil. Returns a time.Duration
// zero value if the pointer was nil.
func ToDurationSlice(vs []*time.Duration) []time.Duration {
ps := make([]time.Duration, len(vs))
for i, v := range vs {
ps[i] = ToDuration(v)
}
return ps
}
// ToDurationMap returns a map of time.Duration values, that are
// dereferenced if the passed in pointer was not nil. The time.Duration
// zero value is used if the pointer was nil.
func ToDurationMap(vs map[string]*time.Duration) map[string]time.Duration {
ps := make(map[string]time.Duration, len(vs))
for k, v := range vs {
ps[k] = ToDuration(v)
}
return ps
}

View File

@@ -23,6 +23,7 @@ func GetScalars() Scalars {
{Type: "float32"},
{Type: "float64"},
{Type: "Time", Import: &Import{Path: "time"}},
{Type: "Duration", Import: &Import{Path: "time"}},
}
}

View File

@@ -468,3 +468,32 @@ func TimeMap(vs map[string]time.Time) map[string]*time.Time {
return ps
}
// Duration returns a pointer value for the time.Duration value passed in.
func Duration(v time.Duration) *time.Duration {
return &v
}
// DurationSlice returns a slice of time.Duration pointers from the values
// passed in.
func DurationSlice(vs []time.Duration) []*time.Duration {
ps := make([]*time.Duration, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// DurationMap returns a map of time.Duration pointers from the values
// passed in.
func DurationMap(vs map[string]time.Duration) map[string]*time.Duration {
ps := make(map[string]*time.Duration, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}

View File

@@ -25,7 +25,7 @@ func Int63n(reader io.Reader, max int64) (int64, error) {
}
// CryptoRandInt63n returns a random int64 between zero and value of max
//obtained from the crypto rand source.
// obtained from the crypto rand source.
func CryptoRandInt63n(max int64) (int64, error) {
return Int63n(Reader, max)
}

View File

@@ -51,4 +51,3 @@ func (e *OnceErr) SetError(err error) {
func (e *OnceErr) ErrorSet() <-chan struct{} {
return e.ch
}

View File

@@ -24,14 +24,14 @@ const (
var millisecondFloat = big.NewFloat(1e3)
// FormatDateTime format value as a date-time, (RFC3339 section 5.6)
// FormatDateTime formats value as a date-time, (RFC3339 section 5.6)
//
// Example: 1985-04-12T23:20:50.52Z
func FormatDateTime(value time.Time) string {
return value.UTC().Format(dateTimeFormatOutput)
}
// ParseDateTime parse a string as a date-time, (RFC3339 section 5.6)
// ParseDateTime parses a string as a date-time, (RFC3339 section 5.6)
//
// Example: 1985-04-12T23:20:50.52Z
func ParseDateTime(value string) (time.Time, error) {
@@ -43,14 +43,14 @@ func ParseDateTime(value string) (time.Time, error) {
)
}
// FormatHTTPDate format value as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate)
// FormatHTTPDate formats value as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate)
//
// Example: Tue, 29 Apr 2014 18:30:38 GMT
func FormatHTTPDate(value time.Time) string {
return value.UTC().Format(httpDateFormat)
}
// ParseHTTPDate parse a string as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate)
// ParseHTTPDate parses a string as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate)
//
// Example: Tue, 29 Apr 2014 18:30:38 GMT
func ParseHTTPDate(value string) (time.Time, error) {
@@ -116,8 +116,8 @@ type parseError struct {
Err error
}
// SleepWithContext will wait for the timer duration to expire, or the context
// is canceled. Which ever happens first. If the context is canceled the
// SleepWithContext will wait for the timer duration to expire, or until the context
// is canceled. Whichever happens first. If the context is canceled the
// Context's error will be returned.
func SleepWithContext(ctx context.Context, dur time.Duration) error {
t := time.NewTimer(dur)

View File

@@ -21,7 +21,7 @@ func AddContentChecksumMiddleware(stack *middleware.Stack) error {
return stack.Build.Add(&contentMD5Checksum{}, middleware.Before)
}
// ID the identifier for the checksum middleware
// ID returns the identifier for the checksum middleware
func (m *contentMD5Checksum) ID() string { return "ContentChecksum" }
// HandleBuild adds behavior to compute md5 checksum and add content-md5 header
@@ -45,6 +45,11 @@ func (m *contentMD5Checksum) HandleBuild(
stream := req.GetStream()
// compute checksum if payload is explicit
if stream != nil {
if !req.IsStreamSeekable() {
return out, metadata, fmt.Errorf(
"unseekable stream is not supported for computing md5 checksum")
}
v, err := computeMD5Checksum(stream)
if err != nil {
return out, metadata, fmt.Errorf("error computing md5 checksum, %w", err)

View File

@@ -14,7 +14,7 @@ type ClientDo interface {
Do(*http.Request) (*http.Response, error)
}
// ClientDoFunc provides a helper to wrap an function as an HTTP client for
// ClientDoFunc provides a helper to wrap a function as an HTTP client for
// round tripping requests.
type ClientDoFunc func(*http.Request) (*http.Response, error)
@@ -37,7 +37,7 @@ func NewClientHandler(client ClientDo) ClientHandler {
}
// Handle implements the middleware Handler interface, that will invoke the
// underlying HTTP client. Requires the input to be an Smithy *Request. Returns
// underlying HTTP client. Requires the input to be a Smithy *Request. Returns
// a smithy *Response, or error if the request failed.
func (c ClientHandler) Handle(ctx context.Context, input interface{}) (
out interface{}, metadata middleware.Metadata, err error,
@@ -91,7 +91,7 @@ type RequestSendError struct {
Err error
}
// ConnectionError return that the error is related to not being able to send
// ConnectionError returns that the error is related to not being able to send
// the request, or receive a response from the service.
func (e *RequestSendError) ConnectionError() bool {
return true
@@ -106,7 +106,7 @@ func (e *RequestSendError) Error() string {
return fmt.Sprintf("request send failed, %v", e.Err)
}
// NopClient provides a client that ignores the request, and returns a empty
// NopClient provides a client that ignores the request, and returns an empty
// successful HTTP response value.
type NopClient struct{}

View File

@@ -2,53 +2,125 @@ package http
import (
"fmt"
"strconv"
"strings"
"unicode"
)
func splitHeaderListValues(vs []string, splitFn func(string) ([]string, error)) ([]string, error) {
for i := 0; i < len(vs); i++ {
if len(vs[i]) == 0 {
continue
}
values := make([]string, 0, len(vs))
for i := 0; i < len(vs); i++ {
parts, err := splitFn(vs[i])
if err != nil {
return nil, err
}
if len(parts) < 2 {
continue
}
tmp := make([]string, len(vs)+len(parts)-1)
copy(tmp, vs[:i])
for j, p := range parts {
tmp[i+j] = strings.TrimSpace(p)
}
copy(tmp[i+len(parts):], vs[i+1:])
vs = tmp
i += len(parts) - 1
values = append(values, parts...)
}
return vs, nil
return values, nil
}
// SplitHeaderListValues attempts to split the elements of the slice by commas,
// and return a list of all values separated. Returns error if unable to
// separate the values.
func SplitHeaderListValues(vs []string) ([]string, error) {
return splitHeaderListValues(vs, commaSplit)
return splitHeaderListValues(vs, quotedCommaSplit)
}
func commaSplit(v string) ([]string, error) {
return strings.Split(v, ","), nil
func quotedCommaSplit(v string) (parts []string, err error) {
v = strings.TrimSpace(v)
expectMore := true
for i := 0; i < len(v); i++ {
if unicode.IsSpace(rune(v[i])) {
continue
}
expectMore = false
// leading space in part is ignored.
// Start of value must be non-space, or quote.
//
// - If quote, enter quoted mode, find next non-escaped quote to
// terminate the value.
// - Otherwise, find next comma to terminate value.
remaining := v[i:]
var value string
var valueLen int
if remaining[0] == '"' {
//------------------------------
// Quoted value
//------------------------------
var j int
var skipQuote bool
for j += 1; j < len(remaining); j++ {
if remaining[j] == '\\' || (remaining[j] != '\\' && skipQuote) {
skipQuote = !skipQuote
continue
}
if remaining[j] == '"' {
break
}
}
if j == len(remaining) || j == 1 {
return nil, fmt.Errorf("value %v missing closing double quote",
remaining)
}
valueLen = j + 1
tail := remaining[valueLen:]
var k int
for ; k < len(tail); k++ {
if !unicode.IsSpace(rune(tail[k])) && tail[k] != ',' {
return nil, fmt.Errorf("value %v has non-space trailing characters",
remaining)
}
if tail[k] == ',' {
expectMore = true
break
}
}
value = remaining[:valueLen]
value, err = strconv.Unquote(value)
if err != nil {
return nil, fmt.Errorf("failed to unquote value %v, %w", value, err)
}
// Pad valueLen to include trailing space(s) so `i` is updated correctly.
valueLen += k
} else {
//------------------------------
// Unquoted value
//------------------------------
// Index of the next comma is the length of the value, or end of string.
valueLen = strings.Index(remaining, ",")
if valueLen != -1 {
expectMore = true
} else {
valueLen = len(remaining)
}
value = strings.TrimSpace(remaining[:valueLen])
}
i += valueLen
parts = append(parts, value)
}
if expectMore {
parts = append(parts, "")
}
return parts, nil
}
// SplitHTTPDateTimestampHeaderListValues attempts to split the HTTP-Date
// timestamp values in the slice by commas, and return a list of all values
// separated. The split is aware of HTTP-Date timestamp format, and will skip
// separated. The split is aware of the HTTP-Date timestamp format, and will skip
// comma within the timestamp value. Returns an error if unable to split the
// timestamp values.
func SplitHTTPDateTimestampHeaderListValues(vs []string) ([]string, error) {
@@ -56,10 +128,10 @@ func SplitHTTPDateTimestampHeaderListValues(vs []string) ([]string, error) {
}
func splitHTTPDateHeaderValue(v string) ([]string, error) {
if n := strings.Count(v, ","); n == 1 {
// Skip values with only a single HTTPDate value
return nil, nil
} else if n == 0 || n%2 == 0 {
if n := strings.Count(v, ","); n <= 1 {
// Nothing to do if only contains a no, or single HTTPDate value
return []string{v}, nil
} else if n%2 == 0 {
return nil, fmt.Errorf("invalid timestamp HTTPDate header comma separations, %q", v)
}
@@ -71,7 +143,7 @@ func splitHTTPDateHeaderValue(v string) ([]string, error) {
if v[i] == ',' {
if doSplit {
doSplit = false
parts = append(parts, v[j:i])
parts = append(parts, strings.TrimSpace(v[j:i]))
j = i + 1
} else {
// Skip the first comma in the timestamp value since that
@@ -82,8 +154,9 @@ func splitHTTPDateHeaderValue(v string) ([]string, error) {
}
}
}
// Add final part
if j < len(v) {
parts = append(parts, v[j:])
parts = append(parts, strings.TrimSpace(v[j:]))
}
return parts, nil

View File

@@ -56,7 +56,7 @@ func ValidateEndpointHost(host string) error {
return nil
}
// ValidPortNumber return if the port is valid RFC 3986 port
// ValidPortNumber returns whether the port is valid RFC 3986 port.
func ValidPortNumber(port string) bool {
i, err := strconv.Atoi(port)
if err != nil {
@@ -69,7 +69,7 @@ func ValidPortNumber(port string) bool {
return true
}
// ValidHostLabel returns if the label is a valid RFC 3986 host label.
// ValidHostLabel returns whether the label is a valid RFC 3986 host abel.
func ValidHostLabel(label string) bool {
if l := len(label); l == 0 || l > 63 {
return false

View File

@@ -7,7 +7,7 @@ import (
"io"
)
// computeMD5Checksum computes base64 md5 checksum of an io.Reader contents.
// computeMD5Checksum computes base64 md5 checksum of an io.Reader's contents.
// Returns the byte slice of md5 checksum and an error.
func computeMD5Checksum(r io.Reader) ([]byte, error) {
h := md5.New()

View File

@@ -18,7 +18,7 @@ func AddComputeContentLengthMiddleware(stack *middleware.Stack) error {
return stack.Build.Add(&ComputeContentLength{}, middleware.After)
}
// ID the identifier for the ComputeContentLength
// ID returns the identifier for the ComputeContentLength.
func (m *ComputeContentLength) ID() string { return "ComputeContentLength" }
// HandleBuild adds the length of the serialized request to the HTTP header
@@ -44,12 +44,6 @@ func (m *ComputeContentLength) HandleBuild(
"failed getting length of request stream, %w", err)
} else if ok {
req.ContentLength = n
if n == 0 {
// If the content length could be determined, and the body is empty
// the stream must be cleared to prevent unexpected chunk encoding.
req, _ = req.SetStream(nil)
in.Request = req
}
}
return next.HandleBuild(ctx, in)
@@ -65,7 +59,7 @@ func ValidateContentLengthHeader(stack *middleware.Stack) error {
return stack.Build.Add(&validateContentLength{}, middleware.After)
}
// ID the identifier for the ComputeContentLength
// ID returns the identifier for the ComputeContentLength.
func (m *validateContentLength) ID() string { return "ValidateContentLength" }
// HandleBuild adds the length of the serialized request to the HTTP header

View File

@@ -11,7 +11,7 @@ type (
hostPrefixDisableKey struct{}
)
// GetHostnameImmutable retrieves if the endpoint hostname should be considered
// GetHostnameImmutable retrieves whether the endpoint hostname should be considered
// immutable or not.
//
// Scoped to stack values. Use middleware#ClearStackValues to clear all stack
@@ -21,7 +21,7 @@ func GetHostnameImmutable(ctx context.Context) (v bool) {
return v
}
// SetHostnameImmutable sets or modifies if the request's endpoint hostname
// SetHostnameImmutable sets or modifies whether the request's endpoint hostname
// should be considered immutable or not.
//
// Scoped to stack values. Use middleware#ClearStackValues to clear all stack
@@ -30,7 +30,7 @@ func SetHostnameImmutable(ctx context.Context, value bool) context.Context {
return middleware.WithStackValue(ctx, hostnameImmutableKey{}, value)
}
// IsEndpointHostPrefixDisabled retrieves if the hostname prefixing is
// IsEndpointHostPrefixDisabled retrieves whether the hostname prefixing is
// disabled.
//
// Scoped to stack values. Use middleware#ClearStackValues to clear all stack
@@ -40,8 +40,8 @@ func IsEndpointHostPrefixDisabled(ctx context.Context) (v bool) {
return v
}
// DisableEndpointHostPrefix sets or modifies if the request's endpoint host
// prefixing to be disabled. If value is set to true, endpoint host prefixing
// DisableEndpointHostPrefix sets or modifies whether the request's endpoint host
// prefixing should be disabled. If value is true, endpoint host prefixing
// will be disabled.
//
// Scoped to stack values. Use middleware#ClearStackValues to clear all stack

View File

@@ -20,7 +20,7 @@ type Request struct {
streamStartPos int64
}
// NewStackRequest returns an initialized request ready to populated with the
// NewStackRequest returns an initialized request ready to be populated with the
// HTTP request details. Returns empty interface so the function can be used as
// a parameter to the Smithy middleware Stack constructor.
func NewStackRequest() interface{} {
@@ -45,19 +45,23 @@ func (r *Request) Clone() *Request {
// to the request and ok set. If the length cannot be determined, an error will
// be returned.
func (r *Request) StreamLength() (size int64, ok bool, err error) {
if r.stream == nil {
return streamLength(r.stream, r.isStreamSeekable, r.streamStartPos)
}
func streamLength(stream io.Reader, seekable bool, startPos int64) (size int64, ok bool, err error) {
if stream == nil {
return 0, true, nil
}
if l, ok := r.stream.(interface{ Len() int }); ok {
if l, ok := stream.(interface{ Len() int }); ok {
return int64(l.Len()), true, nil
}
if !r.isStreamSeekable {
if !seekable {
return 0, false, nil
}
s := r.stream.(io.Seeker)
s := stream.(io.Seeker)
endOffset, err := s.Seek(0, io.SeekEnd)
if err != nil {
return 0, false, err
@@ -69,12 +73,12 @@ func (r *Request) StreamLength() (size int64, ok bool, err error) {
// file, and wants to skip the first N bytes uploading the rest. The
// application would move the file's offset N bytes, then hand it off to
// the SDK to send the remaining. The SDK should respect that initial offset.
_, err = s.Seek(r.streamStartPos, io.SeekStart)
_, err = s.Seek(startPos, io.SeekStart)
if err != nil {
return 0, false, err
}
return endOffset - r.streamStartPos, true, nil
return endOffset - startPos, true, nil
}
// RewindStream will rewind the io.Reader to the relative start position if it
@@ -98,28 +102,46 @@ func (r *Request) GetStream() io.Reader {
return r.stream
}
// IsStreamSeekable returns if the stream is seekable.
// IsStreamSeekable returns whether the stream is seekable.
func (r *Request) IsStreamSeekable() bool {
return r.isStreamSeekable
}
// SetStream returns a clone of the request with the stream set to the provided reader.
// May return an error if the provided reader is seekable but returns an error.
// SetStream returns a clone of the request with the stream set to the provided
// reader. May return an error if the provided reader is seekable but returns
// an error.
func (r *Request) SetStream(reader io.Reader) (rc *Request, err error) {
rc = r.Clone()
if reader == http.NoBody {
reader = nil
}
var isStreamSeekable bool
var streamStartPos int64
switch v := reader.(type) {
case io.Seeker:
n, err := v.Seek(0, io.SeekCurrent)
if err != nil {
return r, err
}
rc.isStreamSeekable = true
rc.streamStartPos = n
isStreamSeekable = true
streamStartPos = n
default:
rc.isStreamSeekable = false
// If the stream length can be determined, and is determined to be empty,
// use a nil stream to prevent confusion between empty vs not-empty
// streams.
length, ok, err := streamLength(reader, false, 0)
if err != nil {
return nil, err
} else if ok && length == 0 {
reader = nil
}
}
rc.stream = reader
rc.isStreamSeekable = isStreamSeekable
rc.streamStartPos = streamStartPos
return rc, err
}
@@ -139,7 +161,11 @@ func (r *Request) Build(ctx context.Context) *http.Request {
req.Body = ioutil.NopCloser(stream)
req.ContentLength = -1
default:
if r.stream != nil {
// HTTP Client Request must only have a non-nil body if the
// ContentLength is explicitly unknown (-1) or non-zero. The HTTP
// Client will interpret a non-nil body and ContentLength 0 as
// "unknown". This is unwanted behavior.
if req.ContentLength != 0 && r.stream != nil {
req.Body = iointernal.NewSafeReadCloser(ioutil.NopCloser(stream))
}
}
@@ -148,7 +174,7 @@ func (r *Request) Build(ctx context.Context) *http.Request {
}
// RequestCloner is a function that can take an input request type and clone the request
// for use in a subsequent retry attempt
// for use in a subsequent retry attempt.
func RequestCloner(v interface{}) interface{} {
return v.(*Request).Clone()
}

View File

@@ -18,7 +18,7 @@ type ResponseError struct {
Err error
}
// HttpStatusCode returns the HTTP response status code received from the service
// HTTPStatusCode returns the HTTP response status code received from the service.
func (e *ResponseError) HTTPStatusCode() int { return e.Response.StatusCode }
// HTTPResponse returns the HTTP response received from the service.

View File

@@ -30,7 +30,7 @@ func (m *Logger) HandleInitialize(ctx context.Context, in middleware.InitializeI
return next.HandleInitialize(ctx, in)
}
// AddLogger is helper util to add waiter logger after `SetLogger` middleware in
// AddLogger is a helper util to add waiter logger after `SetLogger` middleware in
func (m Logger) AddLogger(stack *middleware.Stack) error {
return stack.Initialize.Insert(&m, "SetLogger", middleware.After)
}