Update Godeps to aws-sdk-go v0.9.9.

This commit is contained in:
Trevor Pounds
2015-09-20 13:45:08 -07:00
parent 8236335697
commit b76f6a021c
82 changed files with 22121 additions and 13872 deletions

45
Godeps/Godeps.json generated
View File

@@ -30,58 +30,53 @@
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/aws", "ImportPath": "github.com/aws/aws-sdk-go/aws",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/apierr",
"Comment": "v0.6.0-7-gcea3a42",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/endpoints", "ImportPath": "github.com/aws/aws-sdk-go/internal/endpoints",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/ec2query", "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/ec2query",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/query", "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/query",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/rest", "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/rest",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil", "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/internal/signer/v4", "ImportPath": "github.com/aws/aws-sdk-go/internal/signer/v4",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/service/autoscaling", "ImportPath": "github.com/aws/aws-sdk-go/service/autoscaling",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/service/ec2", "ImportPath": "github.com/aws/aws-sdk-go/service/ec2",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/aws/aws-sdk-go/service/elb", "ImportPath": "github.com/aws/aws-sdk-go/service/elb",
"Comment": "v0.6.0-7-gcea3a42", "Comment": "v0.9.9",
"Rev": "cea3a425fc2d887d102e406ec2f8b37a57abd82f" "Rev": "c4ae871ffc03691a7b039fa751a1e7afee56e920"
}, },
{ {
"ImportPath": "github.com/beorn7/perks/quantile", "ImportPath": "github.com/beorn7/perks/quantile",

View File

@@ -16,7 +16,7 @@ package awserr
// // Get error details // // Get error details
// log.Println("Error:", err.Code(), err.Message()) // log.Println("Error:", err.Code(), err.Message())
// //
// Prints out full error message, including original error if there was one. // // Prints out full error message, including original error if there was one.
// log.Println("Error:", err.Error()) // log.Println("Error:", err.Error())
// //
// // Get original error // // Get original error
@@ -42,6 +42,17 @@ type Error interface {
OrigErr() error OrigErr() error
} }
// New returns an Error object described by the code, message, and origErr.
//
// If origErr satisfies the Error interface it will not be wrapped within a new
// Error object and will instead be returned.
func New(code, message string, origErr error) Error {
if e, ok := origErr.(Error); ok && e != nil {
return e
}
return newBaseError(code, message, origErr)
}
// A RequestFailure is an interface to extract request failure information from // A RequestFailure is an interface to extract request failure information from
// an Error such as the request ID of the failed request returned by a service. // an Error such as the request ID of the failed request returned by a service.
// RequestFailures may not always have a requestID value if the request failed // RequestFailures may not always have a requestID value if the request failed
@@ -86,3 +97,9 @@ type RequestFailure interface {
// to a connection error. // to a connection error.
RequestID() string RequestID() string
} }
// NewRequestFailure returns a new request error wrapper for the given Error
// provided.
func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure {
return newRequestError(err, statusCode, reqID)
}

View File

@@ -1,14 +1,28 @@
// Package apierr represents API error types. package awserr
package apierr
import "fmt" import "fmt"
// A BaseError wraps the code and message which defines an error. It also // SprintError returns a string of the formatted error code.
//
// Both extra and origErr are optional. If they are included their lines
// will be added, but if they are not included their lines will be ignored.
func SprintError(code, message, extra string, origErr error) string {
msg := fmt.Sprintf("%s: %s", code, message)
if extra != "" {
msg = fmt.Sprintf("%s\n\t%s", msg, extra)
}
if origErr != nil {
msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error())
}
return msg
}
// A baseError wraps the code and message which defines an error. It also
// can be used to wrap an original error object. // can be used to wrap an original error object.
// //
// Should be used as the root for errors satisfying the awserr.Error. Also // Should be used as the root for errors satisfying the awserr.Error. Also
// for any error which does not fit into a specific error wrapper type. // for any error which does not fit into a specific error wrapper type.
type BaseError struct { type baseError struct {
// Classification of error // Classification of error
code string code string
@@ -20,7 +34,7 @@ type BaseError struct {
origErr error origErr error
} }
// New returns an error object for the code, message, and err. // newBaseError returns an error object for the code, message, and err.
// //
// code is a short no whitespace phrase depicting the classification of // code is a short no whitespace phrase depicting the classification of
// the error that is being created. // the error that is being created.
@@ -28,8 +42,8 @@ type BaseError struct {
// message is the free flow string containing detailed information about the error. // message is the free flow string containing detailed information about the error.
// //
// origErr is the error object which will be nested under the new error to be returned. // origErr is the error object which will be nested under the new error to be returned.
func New(code, message string, origErr error) *BaseError { func newBaseError(code, message string, origErr error) *baseError {
return &BaseError{ return &baseError{
code: code, code: code,
message: message, message: message,
origErr: origErr, origErr: origErr,
@@ -41,75 +55,56 @@ func New(code, message string, origErr error) *BaseError {
// See ErrorWithExtra for formatting. // See ErrorWithExtra for formatting.
// //
// Satisfies the error interface. // Satisfies the error interface.
func (b *BaseError) Error() string { func (b baseError) Error() string {
return b.ErrorWithExtra("") return SprintError(b.code, b.message, "", b.origErr)
} }
// String returns the string representation of the error. // String returns the string representation of the error.
// Alias for Error to satisfy the stringer interface. // Alias for Error to satisfy the stringer interface.
func (b *BaseError) String() string { func (b baseError) String() string {
return b.Error() return b.Error()
} }
// Code returns the short phrase depicting the classification of the error. // Code returns the short phrase depicting the classification of the error.
func (b *BaseError) Code() string { func (b baseError) Code() string {
return b.code return b.code
} }
// Message returns the error details message. // Message returns the error details message.
func (b *BaseError) Message() string { func (b baseError) Message() string {
return b.message return b.message
} }
// OrigErr returns the original error if one was set. Nil is returned if no error // OrigErr returns the original error if one was set. Nil is returned if no error
// was set. // was set.
func (b *BaseError) OrigErr() error { func (b baseError) OrigErr() error {
return b.origErr return b.origErr
} }
// ErrorWithExtra is a helper method to add an extra string to the stratified // So that the Error interface type can be included as an anonymous field
// error message. The extra message will be added on the next line below the // in the requestError struct and not conflict with the error.Error() method.
// error message like the following: type awsError Error
//
// <error code>: <error message>
// <extra message>
//
// If there is a original error the error will be included on a new line.
//
// <error code>: <error message>
// <extra message>
// caused by: <original error>
func (b *BaseError) ErrorWithExtra(extra string) string {
msg := fmt.Sprintf("%s: %s", b.code, b.message)
if extra != "" {
msg = fmt.Sprintf("%s\n\t%s", msg, extra)
}
if b.origErr != nil {
msg = fmt.Sprintf("%s\ncaused by: %s", msg, b.origErr.Error())
}
return msg
}
// A RequestError wraps a request or service error. // A requestError wraps a request or service error.
// //
// Composed of BaseError for code, message, and original error. // Composed of baseError for code, message, and original error.
type RequestError struct { type requestError struct {
*BaseError awsError
statusCode int statusCode int
requestID string requestID string
} }
// NewRequestError returns a wrapped error with additional information for request // newRequestError returns a wrapped error with additional information for request
// status code, and service requestID. // status code, and service requestID.
// //
// Should be used to wrap all request which involve service requests. Even if // Should be used to wrap all request which involve service requests. Even if
// the request failed without a service response, but had an HTTP status code // the request failed without a service response, but had an HTTP status code
// that may be meaningful. // that may be meaningful.
// //
// Also wraps original errors via the BaseError. // Also wraps original errors via the baseError.
func NewRequestError(base *BaseError, statusCode int, requestID string) *RequestError { func newRequestError(err Error, statusCode int, requestID string) *requestError {
return &RequestError{ return &requestError{
BaseError: base, awsError: err,
statusCode: statusCode, statusCode: statusCode,
requestID: requestID, requestID: requestID,
} }
@@ -117,23 +112,24 @@ func NewRequestError(base *BaseError, statusCode int, requestID string) *Request
// Error returns the string representation of the error. // Error returns the string representation of the error.
// Satisfies the error interface. // Satisfies the error interface.
func (r *RequestError) Error() string { func (r requestError) Error() string {
return r.ErrorWithExtra(fmt.Sprintf("status code: %d, request id: [%s]", extra := fmt.Sprintf("status code: %d, request id: %s",
r.statusCode, r.requestID)) r.statusCode, r.requestID)
return SprintError(r.Code(), r.Message(), extra, r.OrigErr())
} }
// String returns the string representation of the error. // String returns the string representation of the error.
// Alias for Error to satisfy the stringer interface. // Alias for Error to satisfy the stringer interface.
func (r *RequestError) String() string { func (r requestError) String() string {
return r.Error() return r.Error()
} }
// StatusCode returns the wrapped status code for the error // StatusCode returns the wrapped status code for the error
func (r *RequestError) StatusCode() int { func (r requestError) StatusCode() int {
return r.statusCode return r.statusCode
} }
// RequestID returns the wrapped requestID // RequestID returns the wrapped requestID
func (r *RequestError) RequestID() string { func (r requestError) RequestID() string {
return r.requestID return r.requestID
} }

View File

@@ -70,12 +70,20 @@ func rcopy(dst, src reflect.Value, root bool) {
} }
} }
case reflect.Slice: case reflect.Slice:
if src.IsNil() {
break
}
s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
dst.Set(s) dst.Set(s)
for i := 0; i < src.Len(); i++ { for i := 0; i < src.Len(); i++ {
rcopy(dst.Index(i), src.Index(i), false) rcopy(dst.Index(i), src.Index(i), false)
} }
case reflect.Map: case reflect.Map:
if src.IsNil() {
break
}
s := reflect.MakeMap(src.Type()) s := reflect.MakeMap(src.Type())
dst.Set(s) dst.Set(s)
for _, k := range src.MapKeys() { for _, k := range src.MapKeys() {

View File

@@ -27,7 +27,7 @@ func ExampleCopy() {
awsutil.Copy(&f2, f1) awsutil.Copy(&f2, f1)
// Print the result // Print the result
fmt.Println(awsutil.StringValue(f2)) fmt.Println(awsutil.Prettify(f2))
// Output: // Output:
// { // {
@@ -80,18 +80,26 @@ func TestCopy(t *testing.T) {
func TestCopyIgnoreNilMembers(t *testing.T) { func TestCopyIgnoreNilMembers(t *testing.T) {
type Foo struct { type Foo struct {
A *string A *string
B []string
C map[string]string
} }
f := &Foo{} f := &Foo{}
assert.Nil(t, f.A) assert.Nil(t, f.A)
assert.Nil(t, f.B)
assert.Nil(t, f.C)
var f2 Foo var f2 Foo
awsutil.Copy(&f2, f) awsutil.Copy(&f2, f)
assert.Nil(t, f2.A) assert.Nil(t, f2.A)
assert.Nil(t, f2.B)
assert.Nil(t, f2.C)
fcopy := awsutil.CopyOf(f) fcopy := awsutil.CopyOf(f)
f3 := fcopy.(*Foo) f3 := fcopy.(*Foo)
assert.Nil(t, f3.A) assert.Nil(t, f3.A)
assert.Nil(t, f3.B)
assert.Nil(t, f3.C)
} }
func TestCopyPrimitive(t *testing.T) { func TestCopyPrimitive(t *testing.T) {
@@ -183,7 +191,7 @@ func ExampleCopyOf() {
var f2 *Foo = v.(*Foo) var f2 *Foo = v.(*Foo)
// Print the result // Print the result
fmt.Println(awsutil.StringValue(f2)) fmt.Println(awsutil.Prettify(f2))
// Output: // Output:
// { // {

View File

@@ -81,6 +81,12 @@ func rValuesAtPath(v interface{}, path string, create bool, caseSensitive bool)
value = reflect.Indirect(value) value = reflect.Indirect(value)
} }
if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
if !create && value.IsNil() {
value = reflect.ValueOf(nil)
}
}
if value.IsValid() { if value.IsValid() {
nextvals = append(nextvals, value) nextvals = append(nextvals, value)
} }
@@ -118,6 +124,12 @@ func rValuesAtPath(v interface{}, path string, create bool, caseSensitive bool)
} }
value = reflect.Indirect(value.Index(i)) value = reflect.Indirect(value.Index(i))
if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
if !create && value.IsNil() {
value = reflect.ValueOf(nil)
}
}
if value.IsValid() { if value.IsValid() {
nextvals = append(nextvals, value) nextvals = append(nextvals, value)
} }

View File

@@ -16,8 +16,8 @@ type Struct struct {
} }
var data = Struct{ var data = Struct{
A: []Struct{Struct{C: "value1"}, Struct{C: "value2"}, Struct{C: "value3"}}, A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
z: []Struct{Struct{C: "value1"}, Struct{C: "value2"}, Struct{C: "value3"}}, z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}},
B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}},
C: "initial", C: "initial",
} }
@@ -44,6 +44,7 @@ func TestValueAtPathFailure(t *testing.T) {
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "B.B.C.Z")) assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "B.B.C.Z"))
assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "z[-1].C")) assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "z[-1].C"))
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(nil, "A.B.C")) assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(nil, "A.B.C"))
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(Struct{}, "A"))
} }
func TestSetValueAtPathSuccess(t *testing.T) { func TestSetValueAtPathSuccess(t *testing.T) {
@@ -62,4 +63,6 @@ func TestSetValueAtPathSuccess(t *testing.T) {
var s2 Struct var s2 Struct
awsutil.SetValueAtAnyPath(&s2, "b.b.c", "test0") awsutil.SetValueAtAnyPath(&s2, "b.b.c", "test0")
assert.Equal(t, "test0", s2.B.B.C) assert.Equal(t, "test0", s2.B.B.C)
awsutil.SetValueAtAnyPath(&s2, "A", []Struct{{}})
assert.Equal(t, []Struct{{}}, s2.A)
} }

View File

@@ -8,16 +8,16 @@ import (
"strings" "strings"
) )
// StringValue returns the string representation of a value. // Prettify returns the string representation of a value.
func StringValue(i interface{}) string { func Prettify(i interface{}) string {
var buf bytes.Buffer var buf bytes.Buffer
stringValue(reflect.ValueOf(i), 0, &buf) prettify(reflect.ValueOf(i), 0, &buf)
return buf.String() return buf.String()
} }
// stringValue will recursively walk value v to build a textual // prettify will recursively walk value v to build a textual
// representation of the value. // representation of the value.
func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { func prettify(v reflect.Value, indent int, buf *bytes.Buffer) {
for v.Kind() == reflect.Ptr { for v.Kind() == reflect.Ptr {
v = v.Elem() v = v.Elem()
} }
@@ -52,7 +52,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
val := v.FieldByName(n) val := v.FieldByName(n)
buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(n + ": ") buf.WriteString(n + ": ")
stringValue(val, indent+2, buf) prettify(val, indent+2, buf)
if i < len(names)-1 { if i < len(names)-1 {
buf.WriteString(",\n") buf.WriteString(",\n")
@@ -68,7 +68,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
buf.WriteString("[" + nl) buf.WriteString("[" + nl)
for i := 0; i < v.Len(); i++ { for i := 0; i < v.Len(); i++ {
buf.WriteString(id2) buf.WriteString(id2)
stringValue(v.Index(i), indent+2, buf) prettify(v.Index(i), indent+2, buf)
if i < v.Len()-1 { if i < v.Len()-1 {
buf.WriteString("," + nl) buf.WriteString("," + nl)
@@ -82,7 +82,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
for i, k := range v.MapKeys() { for i, k := range v.MapKeys() {
buf.WriteString(strings.Repeat(" ", indent+2)) buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(k.String() + ": ") buf.WriteString(k.String() + ": ")
stringValue(v.MapIndex(k), indent+2, buf) prettify(v.MapIndex(k), indent+2, buf)
if i < v.Len()-1 { if i < v.Len()-1 {
buf.WriteString(",\n") buf.WriteString(",\n")

View File

@@ -1,172 +1,239 @@
package aws package aws
import ( import (
"io"
"net/http" "net/http"
"os"
"time" "time"
"github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials"
) )
// DefaultChainCredentials is a Credentials which will find the first available
// credentials Value from the list of Providers.
//
// This should be used in the default case. Once the type of credentials are
// known switching to the specific Credentials will be more efficient.
var DefaultChainCredentials = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&credentials.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
})
// The default number of retries for a service. The value of -1 indicates that // The default number of retries for a service. The value of -1 indicates that
// the service specific retry default will be used. // the service specific retry default will be used.
const DefaultRetries = -1 const DefaultRetries = -1
// DefaultConfig is the default all service configuration will be based off of. // A Config provides service configuration for service clients. By default,
var DefaultConfig = &Config{ // all clients will use the {defaults.DefaultConfig} structure.
Credentials: DefaultChainCredentials,
Endpoint: "",
Region: os.Getenv("AWS_REGION"),
DisableSSL: false,
ManualSend: false,
HTTPClient: http.DefaultClient,
LogHTTPBody: false,
LogLevel: 0,
Logger: os.Stdout,
MaxRetries: DefaultRetries,
DisableParamValidation: false,
DisableComputeChecksums: false,
S3ForcePathStyle: false,
}
// A Config provides service configuration
type Config struct { type Config struct {
// The credentials object to use when signing requests. Defaults to
// {defaults.DefaultChainCredentials}.
Credentials *credentials.Credentials Credentials *credentials.Credentials
Endpoint string
Region string // An optional endpoint URL (hostname only or fully qualified URI)
DisableSSL bool // that overrides the default generated endpoint for a client. Set this
ManualSend bool // to `""` to use the default generated endpoint.
//
// @note You must still provide a `Region` value when specifying an
// endpoint for a client.
Endpoint *string
// The region to send requests to. This parameter is required and must
// be configured globally or on a per-client basis unless otherwise
// noted. A full list of regions is found in the "Regions and Endpoints"
// document.
//
// @see http://docs.aws.amazon.com/general/latest/gr/rande.html
// AWS Regions and Endpoints
Region *string
// Set this to `true` to disable SSL when sending requests. Defaults
// to `false`.
DisableSSL *bool
// The HTTP client to use when sending requests. Defaults to
// `http.DefaultClient`.
HTTPClient *http.Client HTTPClient *http.Client
LogHTTPBody bool
LogLevel uint // An integer value representing the logging level. The default log level
Logger io.Writer // is zero (LogOff), which represents no logging. To enable logging set
MaxRetries int // to a LogLevel Value.
DisableParamValidation bool LogLevel *LogLevelType
DisableComputeChecksums bool
S3ForcePathStyle bool // The logger writer interface to write logging messages to. Defaults to
// standard out.
Logger Logger
// The maximum number of times that a request will be retried for failures.
// Defaults to -1, which defers the max retry setting to the service specific
// configuration.
MaxRetries *int
// Disables semantic parameter validation, which validates input for missing
// required fields and/or other semantic request input errors.
DisableParamValidation *bool
// Disables the computation of request and response checksums, e.g.,
// CRC32 checksums in Amazon DynamoDB.
DisableComputeChecksums *bool
// Set this to `true` to force the request to use path-style addressing,
// i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client will
// use virtual hosted bucket addressing when possible
// (`http://BUCKET.s3.amazonaws.com/KEY`).
//
// @note This configuration option is specific to the Amazon S3 service.
// @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html
// Amazon S3: Virtual Hosting of Buckets
S3ForcePathStyle *bool
SleepDelay func(time.Duration)
} }
// Copy will return a shallow copy of the Config object. // NewConfig returns a new Config pointer that can be chained with builder methods to
func (c Config) Copy() Config { // set multiple configuration values inline without using pointers.
dst := Config{} //
dst.Credentials = c.Credentials // svc := s3.New(aws.NewConfig().WithRegion("us-west-2").WithMaxRetries(10))
dst.Endpoint = c.Endpoint //
dst.Region = c.Region func NewConfig() *Config {
dst.DisableSSL = c.DisableSSL return &Config{}
dst.ManualSend = c.ManualSend
dst.HTTPClient = c.HTTPClient
dst.LogLevel = c.LogLevel
dst.Logger = c.Logger
dst.MaxRetries = c.MaxRetries
dst.DisableParamValidation = c.DisableParamValidation
dst.DisableComputeChecksums = c.DisableComputeChecksums
dst.S3ForcePathStyle = c.S3ForcePathStyle
return dst
} }
// Merge merges the newcfg attribute values into this Config. Each attribute // WithCredentials sets a config Credentials value returning a Config pointer
// will be merged into this config if the newcfg attribute's value is non-zero. // for chaining.
// Due to this, newcfg attributes with zero values cannot be merged in. For func (c *Config) WithCredentials(creds *credentials.Credentials) *Config {
// example bool attributes cannot be cleared using Merge, and must be explicitly c.Credentials = creds
// set on the Config structure. return c
func (c Config) Merge(newcfg *Config) *Config { }
if newcfg == nil {
// WithEndpoint sets a config Endpoint value returning a Config pointer for
// chaining.
func (c *Config) WithEndpoint(endpoint string) *Config {
c.Endpoint = &endpoint
return c
}
// WithRegion sets a config Region value returning a Config pointer for
// chaining.
func (c *Config) WithRegion(region string) *Config {
c.Region = &region
return c
}
// WithDisableSSL sets a config DisableSSL value returning a Config pointer
// for chaining.
func (c *Config) WithDisableSSL(disable bool) *Config {
c.DisableSSL = &disable
return c
}
// WithHTTPClient sets a config HTTPClient value returning a Config pointer
// for chaining.
func (c *Config) WithHTTPClient(client *http.Client) *Config {
c.HTTPClient = client
return c
}
// WithMaxRetries sets a config MaxRetries value returning a Config pointer
// for chaining.
func (c *Config) WithMaxRetries(max int) *Config {
c.MaxRetries = &max
return c
}
// WithDisableParamValidation sets a config DisableParamValidation value
// returning a Config pointer for chaining.
func (c *Config) WithDisableParamValidation(disable bool) *Config {
c.DisableParamValidation = &disable
return c
}
// WithDisableComputeChecksums sets a config DisableComputeChecksums value
// returning a Config pointer for chaining.
func (c *Config) WithDisableComputeChecksums(disable bool) *Config {
c.DisableComputeChecksums = &disable
return c
}
// WithLogLevel sets a config LogLevel value returning a Config pointer for
// chaining.
func (c *Config) WithLogLevel(level LogLevelType) *Config {
c.LogLevel = &level
return c
}
// WithLogger sets a config Logger value returning a Config pointer for
// chaining.
func (c *Config) WithLogger(logger Logger) *Config {
c.Logger = logger
return c
}
// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config
// pointer for chaining.
func (c *Config) WithS3ForcePathStyle(force bool) *Config {
c.S3ForcePathStyle = &force
return c
}
// WithSleepDelay overrides the function used to sleep while waiting for the
// next retry. Defaults to time.Sleep.
func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config {
c.SleepDelay = fn
return c
}
// Merge returns a new Config with the other Config's attribute values merged into
// this Config. If the other Config's attribute is nil it will not be merged into
// the new Config to be returned.
func (c Config) Merge(other *Config) *Config {
if other == nil {
return &c return &c
} }
cfg := Config{} dst := c
if newcfg != nil && newcfg.Credentials != nil { if other.Credentials != nil {
cfg.Credentials = newcfg.Credentials dst.Credentials = other.Credentials
} else {
cfg.Credentials = c.Credentials
} }
if newcfg != nil && newcfg.Endpoint != "" { if other.Endpoint != nil {
cfg.Endpoint = newcfg.Endpoint dst.Endpoint = other.Endpoint
} else {
cfg.Endpoint = c.Endpoint
} }
if newcfg != nil && newcfg.Region != "" { if other.Region != nil {
cfg.Region = newcfg.Region dst.Region = other.Region
} else {
cfg.Region = c.Region
} }
if newcfg != nil && newcfg.DisableSSL { if other.DisableSSL != nil {
cfg.DisableSSL = newcfg.DisableSSL dst.DisableSSL = other.DisableSSL
} else {
cfg.DisableSSL = c.DisableSSL
} }
if newcfg != nil && newcfg.ManualSend { if other.HTTPClient != nil {
cfg.ManualSend = newcfg.ManualSend dst.HTTPClient = other.HTTPClient
} else {
cfg.ManualSend = c.ManualSend
} }
if newcfg != nil && newcfg.HTTPClient != nil { if other.LogLevel != nil {
cfg.HTTPClient = newcfg.HTTPClient dst.LogLevel = other.LogLevel
} else {
cfg.HTTPClient = c.HTTPClient
} }
if newcfg != nil && newcfg.LogHTTPBody { if other.Logger != nil {
cfg.LogHTTPBody = newcfg.LogHTTPBody dst.Logger = other.Logger
} else {
cfg.LogHTTPBody = c.LogHTTPBody
} }
if newcfg != nil && newcfg.LogLevel != 0 { if other.MaxRetries != nil {
cfg.LogLevel = newcfg.LogLevel dst.MaxRetries = other.MaxRetries
} else {
cfg.LogLevel = c.LogLevel
} }
if newcfg != nil && newcfg.Logger != nil { if other.DisableParamValidation != nil {
cfg.Logger = newcfg.Logger dst.DisableParamValidation = other.DisableParamValidation
} else {
cfg.Logger = c.Logger
} }
if newcfg != nil && newcfg.MaxRetries != DefaultRetries { if other.DisableComputeChecksums != nil {
cfg.MaxRetries = newcfg.MaxRetries dst.DisableComputeChecksums = other.DisableComputeChecksums
} else {
cfg.MaxRetries = c.MaxRetries
} }
if newcfg != nil && newcfg.DisableParamValidation { if other.S3ForcePathStyle != nil {
cfg.DisableParamValidation = newcfg.DisableParamValidation dst.S3ForcePathStyle = other.S3ForcePathStyle
} else {
cfg.DisableParamValidation = c.DisableParamValidation
} }
if newcfg != nil && newcfg.DisableComputeChecksums { if other.SleepDelay != nil {
cfg.DisableComputeChecksums = newcfg.DisableComputeChecksums dst.SleepDelay = other.SleepDelay
} else {
cfg.DisableComputeChecksums = c.DisableComputeChecksums
} }
if newcfg != nil && newcfg.S3ForcePathStyle { return &dst
cfg.S3ForcePathStyle = newcfg.S3ForcePathStyle }
} else {
cfg.S3ForcePathStyle = c.S3ForcePathStyle // Copy will return a shallow copy of the Config object.
} func (c Config) Copy() *Config {
dst := c
return &cfg return &dst
} }

View File

@@ -0,0 +1,80 @@
package aws
import (
"net/http"
"reflect"
"testing"
"github.com/aws/aws-sdk-go/aws/credentials"
)
var testCredentials = credentials.NewStaticCredentials("AKID", "SECRET", "SESSION")
var copyTestConfig = Config{
Credentials: testCredentials,
Endpoint: String("CopyTestEndpoint"),
Region: String("COPY_TEST_AWS_REGION"),
DisableSSL: Bool(true),
HTTPClient: http.DefaultClient,
LogLevel: LogLevel(LogDebug),
Logger: NewDefaultLogger(),
MaxRetries: Int(DefaultRetries),
DisableParamValidation: Bool(true),
DisableComputeChecksums: Bool(true),
S3ForcePathStyle: Bool(true),
}
func TestCopy(t *testing.T) {
want := copyTestConfig
got := copyTestConfig.Copy()
if !reflect.DeepEqual(*got, want) {
t.Errorf("Copy() = %+v", got)
t.Errorf(" want %+v", want)
}
}
func TestCopyReturnsNewInstance(t *testing.T) {
want := copyTestConfig
got := copyTestConfig.Copy()
if got == &want {
t.Errorf("Copy() = %p; want different instance as source %p", got, &want)
}
}
var mergeTestZeroValueConfig = Config{}
var mergeTestConfig = Config{
Credentials: testCredentials,
Endpoint: String("MergeTestEndpoint"),
Region: String("MERGE_TEST_AWS_REGION"),
DisableSSL: Bool(true),
HTTPClient: http.DefaultClient,
LogLevel: LogLevel(LogDebug),
Logger: NewDefaultLogger(),
MaxRetries: Int(10),
DisableParamValidation: Bool(true),
DisableComputeChecksums: Bool(true),
S3ForcePathStyle: Bool(true),
}
var mergeTests = []struct {
cfg *Config
in *Config
want *Config
}{
{&Config{}, nil, &Config{}},
{&Config{}, &mergeTestZeroValueConfig, &Config{}},
{&Config{}, &mergeTestConfig, &mergeTestConfig},
}
func TestMerge(t *testing.T) {
for i, tt := range mergeTests {
got := tt.cfg.Merge(tt.in)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Config %d %+v", i, tt.cfg)
t.Errorf(" Merge(%+v)", tt.in)
t.Errorf(" got %+v", got)
t.Errorf(" want %+v", tt.want)
}
}
}

View File

@@ -0,0 +1,357 @@
package aws
import "time"
// String returns a pointer to of the string value passed in.
func String(v string) *string {
return &v
}
// StringValue returns the value of the string pointer passed in or
// "" if the pointer is nil.
func StringValue(v *string) string {
if v != nil {
return *v
}
return ""
}
// StringSlice converts a slice of string values into a slice of
// string pointers
func StringSlice(src []string) []*string {
dst := make([]*string, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// StringValueSlice converts a slice of string pointers into a slice of
// string values
func StringValueSlice(src []*string) []string {
dst := make([]string, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// StringMap converts a string map of string values into a string
// map of string pointers
func StringMap(src map[string]string) map[string]*string {
dst := make(map[string]*string)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// StringValueMap converts a string map of string pointers into a string
// map of string values
func StringValueMap(src map[string]*string) map[string]string {
dst := make(map[string]string)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Bool returns a pointer to of the bool value passed in.
func Bool(v bool) *bool {
return &v
}
// BoolValue returns the value of the bool pointer passed in or
// false if the pointer is nil.
func BoolValue(v *bool) bool {
if v != nil {
return *v
}
return false
}
// BoolSlice converts a slice of bool values into a slice of
// bool pointers
func BoolSlice(src []bool) []*bool {
dst := make([]*bool, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// BoolValueSlice converts a slice of bool pointers into a slice of
// bool values
func BoolValueSlice(src []*bool) []bool {
dst := make([]bool, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// BoolMap converts a string map of bool values into a string
// map of bool pointers
func BoolMap(src map[string]bool) map[string]*bool {
dst := make(map[string]*bool)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// BoolValueMap converts a string map of bool pointers into a string
// map of bool values
func BoolValueMap(src map[string]*bool) map[string]bool {
dst := make(map[string]bool)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Int returns a pointer to of the int value passed in.
func Int(v int) *int {
return &v
}
// IntValue returns the value of the int pointer passed in or
// 0 if the pointer is nil.
func IntValue(v *int) int {
if v != nil {
return *v
}
return 0
}
// IntSlice converts a slice of int values into a slice of
// int pointers
func IntSlice(src []int) []*int {
dst := make([]*int, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// IntValueSlice converts a slice of int pointers into a slice of
// int values
func IntValueSlice(src []*int) []int {
dst := make([]int, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// IntMap converts a string map of int values into a string
// map of int pointers
func IntMap(src map[string]int) map[string]*int {
dst := make(map[string]*int)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// IntValueMap converts a string map of int pointers into a string
// map of int values
func IntValueMap(src map[string]*int) map[string]int {
dst := make(map[string]int)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Int64 returns a pointer to of the int64 value passed in.
func Int64(v int64) *int64 {
return &v
}
// Int64Value returns the value of the int64 pointer passed in or
// 0 if the pointer is nil.
func Int64Value(v *int64) int64 {
if v != nil {
return *v
}
return 0
}
// Int64Slice converts a slice of int64 values into a slice of
// int64 pointers
func Int64Slice(src []int64) []*int64 {
dst := make([]*int64, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Int64ValueSlice converts a slice of int64 pointers into a slice of
// int64 values
func Int64ValueSlice(src []*int64) []int64 {
dst := make([]int64, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Int64Map converts a string map of int64 values into a string
// map of int64 pointers
func Int64Map(src map[string]int64) map[string]*int64 {
dst := make(map[string]*int64)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Int64ValueMap converts a string map of int64 pointers into a string
// map of int64 values
func Int64ValueMap(src map[string]*int64) map[string]int64 {
dst := make(map[string]int64)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Float64 returns a pointer to of the float64 value passed in.
func Float64(v float64) *float64 {
return &v
}
// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.
func Float64Value(v *float64) float64 {
if v != nil {
return *v
}
return 0
}
// Float64Slice converts a slice of float64 values into a slice of
// float64 pointers
func Float64Slice(src []float64) []*float64 {
dst := make([]*float64, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Float64ValueSlice converts a slice of float64 pointers into a slice of
// float64 values
func Float64ValueSlice(src []*float64) []float64 {
dst := make([]float64, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Float64Map converts a string map of float64 values into a string
// map of float64 pointers
func Float64Map(src map[string]float64) map[string]*float64 {
dst := make(map[string]*float64)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Float64ValueMap converts a string map of float64 pointers into a string
// map of float64 values
func Float64ValueMap(src map[string]*float64) map[string]float64 {
dst := make(map[string]float64)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Time returns a pointer to of the time.Time value passed in.
func Time(v time.Time) *time.Time {
return &v
}
// TimeValue returns the value of the time.Time pointer passed in or
// time.Time{} if the pointer is nil.
func TimeValue(v *time.Time) time.Time {
if v != nil {
return *v
}
return time.Time{}
}
// TimeSlice converts a slice of time.Time values into a slice of
// time.Time pointers
func TimeSlice(src []time.Time) []*time.Time {
dst := make([]*time.Time, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// TimeValueSlice converts a slice of time.Time pointers into a slice of
// time.Time values
func TimeValueSlice(src []*time.Time) []time.Time {
dst := make([]time.Time, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// TimeMap converts a string map of time.Time values into a string
// map of time.Time pointers
func TimeMap(src map[string]time.Time) map[string]*time.Time {
dst := make(map[string]*time.Time)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// TimeValueMap converts a string map of time.Time pointers into a string
// map of time.Time values
func TimeValueMap(src map[string]*time.Time) map[string]time.Time {
dst := make(map[string]time.Time)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}

View File

@@ -0,0 +1,437 @@
package aws
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var testCasesStringSlice = [][]string{
{"a", "b", "c", "d", "e"},
{"a", "b", "", "", "e"},
}
func TestStringSlice(t *testing.T) {
for idx, in := range testCasesStringSlice {
if in == nil {
continue
}
out := StringSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := StringValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesStringValueSlice = [][]*string{
{String("a"), String("b"), nil, String("c")},
}
func TestStringValueSlice(t *testing.T) {
for idx, in := range testCasesStringValueSlice {
if in == nil {
continue
}
out := StringValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := StringSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesStringMap = []map[string]string{
{"a": "1", "b": "2", "c": "3"},
}
func TestStringMap(t *testing.T) {
for idx, in := range testCasesStringMap {
if in == nil {
continue
}
out := StringMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := StringValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesBoolSlice = [][]bool{
{true, true, false, false},
}
func TestBoolSlice(t *testing.T) {
for idx, in := range testCasesBoolSlice {
if in == nil {
continue
}
out := BoolSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := BoolValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesBoolValueSlice = [][]*bool{}
func TestBoolValueSlice(t *testing.T) {
for idx, in := range testCasesBoolValueSlice {
if in == nil {
continue
}
out := BoolValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := BoolSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesBoolMap = []map[string]bool{
{"a": true, "b": false, "c": true},
}
func TestBoolMap(t *testing.T) {
for idx, in := range testCasesBoolMap {
if in == nil {
continue
}
out := BoolMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := BoolValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesIntSlice = [][]int{
{1, 2, 3, 4},
}
func TestIntSlice(t *testing.T) {
for idx, in := range testCasesIntSlice {
if in == nil {
continue
}
out := IntSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := IntValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesIntValueSlice = [][]*int{}
func TestIntValueSlice(t *testing.T) {
for idx, in := range testCasesIntValueSlice {
if in == nil {
continue
}
out := IntValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := IntSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesIntMap = []map[string]int{
{"a": 3, "b": 2, "c": 1},
}
func TestIntMap(t *testing.T) {
for idx, in := range testCasesIntMap {
if in == nil {
continue
}
out := IntMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := IntValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesInt64Slice = [][]int64{
{1, 2, 3, 4},
}
func TestInt64Slice(t *testing.T) {
for idx, in := range testCasesInt64Slice {
if in == nil {
continue
}
out := Int64Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int64ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesInt64ValueSlice = [][]*int64{}
func TestInt64ValueSlice(t *testing.T) {
for idx, in := range testCasesInt64ValueSlice {
if in == nil {
continue
}
out := Int64ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Int64Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesInt64Map = []map[string]int64{
{"a": 3, "b": 2, "c": 1},
}
func TestInt64Map(t *testing.T) {
for idx, in := range testCasesInt64Map {
if in == nil {
continue
}
out := Int64Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Int64ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesFloat64Slice = [][]float64{
{1, 2, 3, 4},
}
func TestFloat64Slice(t *testing.T) {
for idx, in := range testCasesFloat64Slice {
if in == nil {
continue
}
out := Float64Slice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float64ValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesFloat64ValueSlice = [][]*float64{}
func TestFloat64ValueSlice(t *testing.T) {
for idx, in := range testCasesFloat64ValueSlice {
if in == nil {
continue
}
out := Float64ValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := Float64Slice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesFloat64Map = []map[string]float64{
{"a": 3, "b": 2, "c": 1},
}
func TestFloat64Map(t *testing.T) {
for idx, in := range testCasesFloat64Map {
if in == nil {
continue
}
out := Float64Map(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := Float64ValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesTimeSlice = [][]time.Time{
{time.Now(), time.Now().AddDate(100, 0, 0)},
}
func TestTimeSlice(t *testing.T) {
for idx, in := range testCasesTimeSlice {
if in == nil {
continue
}
out := TimeSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := TimeValueSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}
var testCasesTimeValueSlice = [][]*time.Time{}
func TestTimeValueSlice(t *testing.T) {
for idx, in := range testCasesTimeValueSlice {
if in == nil {
continue
}
out := TimeValueSlice(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
if in[i] == nil {
assert.Empty(t, out[i], "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, *(in[i]), out[i], "Unexpected value at idx %d", idx)
}
}
out2 := TimeSlice(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
for i := range out2 {
if in[i] == nil {
assert.Empty(t, *(out2[i]), "Unexpected value at idx %d", idx)
} else {
assert.Equal(t, in[i], out2[i], "Unexpected value at idx %d", idx)
}
}
}
}
var testCasesTimeMap = []map[string]time.Time{
{"a": time.Now().AddDate(-100, 0, 0), "b": time.Now()},
}
func TestTimeMap(t *testing.T) {
for idx, in := range testCasesTimeMap {
if in == nil {
continue
}
out := TimeMap(in)
assert.Len(t, out, len(in), "Unexpected len at idx %d", idx)
for i := range out {
assert.Equal(t, in[i], *(out[i]), "Unexpected value at idx %d", idx)
}
out2 := TimeValueMap(out)
assert.Len(t, out2, len(in), "Unexpected len at idx %d", idx)
assert.Equal(t, in, out2, "Unexpected value at idx %d", idx)
}
}

View File

@@ -1,4 +1,4 @@
package aws package corehandlers
import ( import (
"bytes" "bytes"
@@ -9,16 +9,12 @@ import (
"net/url" "net/url"
"regexp" "regexp"
"strconv" "strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
) )
var sleepDelay = func(delay time.Duration) {
time.Sleep(delay)
}
// Interface for matching types which also have a Len method. // Interface for matching types which also have a Len method.
type lener interface { type lener interface {
Len() int Len() int
@@ -27,7 +23,7 @@ type lener interface {
// BuildContentLength builds the content length of a request based on the body, // BuildContentLength builds the content length of a request based on the body,
// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable // or will use the HTTPRequest.Header's "Content-Length" if defined. If unable
// to determine request body length and no "Content-Length" was specified it will panic. // to determine request body length and no "Content-Length" was specified it will panic.
func BuildContentLength(r *Request) { var BuildContentLengthHandler = request.NamedHandler{"core.BuildContentLengthHandler", func(r *request.Request) {
if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" {
length, _ := strconv.ParseInt(slength, 10, 64) length, _ := strconv.ParseInt(slength, 10, 64)
r.HTTPRequest.ContentLength = length r.HTTPRequest.ContentLength = length
@@ -41,27 +37,27 @@ func BuildContentLength(r *Request) {
case lener: case lener:
length = int64(body.Len()) length = int64(body.Len())
case io.Seeker: case io.Seeker:
r.bodyStart, _ = body.Seek(0, 1) r.BodyStart, _ = body.Seek(0, 1)
end, _ := body.Seek(0, 2) end, _ := body.Seek(0, 2)
body.Seek(r.bodyStart, 0) // make sure to seek back to original location body.Seek(r.BodyStart, 0) // make sure to seek back to original location
length = end - r.bodyStart length = end - r.BodyStart
default: default:
panic("Cannot get length of body, must provide `ContentLength`") panic("Cannot get length of body, must provide `ContentLength`")
} }
r.HTTPRequest.ContentLength = length r.HTTPRequest.ContentLength = length
r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length))
} }}
// UserAgentHandler is a request handler for injecting User agent into requests. // UserAgentHandler is a request handler for injecting User agent into requests.
func UserAgentHandler(r *Request) { var UserAgentHandler = request.NamedHandler{"core.UserAgentHandler", func(r *request.Request) {
r.HTTPRequest.Header.Set("User-Agent", SDKName+"/"+SDKVersion) r.HTTPRequest.Header.Set("User-Agent", aws.SDKName+"/"+aws.SDKVersion)
} }}
var reStatusCode = regexp.MustCompile(`^(\d+)`) var reStatusCode = regexp.MustCompile(`^(\d{3})`)
// SendHandler is a request handler to send service request using HTTP client. // SendHandler is a request handler to send service request using HTTP client.
func SendHandler(r *Request) { var SendHandler = request.NamedHandler{"core.SendHandler", func(r *request.Request) {
var err error var err error
r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest) r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest)
if err != nil { if err != nil {
@@ -69,8 +65,8 @@ func SendHandler(r *Request) {
// response. e.g. 301 without location header comes back as string // response. e.g. 301 without location header comes back as string
// error and r.HTTPResponse is nil. Other url redirect errors will // error and r.HTTPResponse is nil. Other url redirect errors will
// comeback in a similar method. // comeback in a similar method.
if e, ok := err.(*url.Error); ok { if e, ok := err.(*url.Error); ok && e.Err != nil {
if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil { if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil {
code, _ := strconv.ParseInt(s[1], 10, 64) code, _ := strconv.ParseInt(s[1], 10, 64)
r.HTTPResponse = &http.Response{ r.HTTPResponse = &http.Response{
StatusCode: int(code), StatusCode: int(code),
@@ -80,68 +76,61 @@ func SendHandler(r *Request) {
return return
} }
} }
// Catch all other request errors. if r.HTTPResponse == nil {
r.Error = apierr.New("RequestError", "send request failed", err) // Add a dummy request response object to ensure the HTTPResponse
r.Retryable.Set(true) // network errors are retryable // value is consistent.
r.HTTPResponse = &http.Response{
StatusCode: int(0),
Status: http.StatusText(int(0)),
Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
} }
} }
// Catch all other request errors.
r.Error = awserr.New("RequestError", "send request failed", err)
r.Retryable = aws.Bool(true) // network errors are retryable
}
}}
// ValidateResponseHandler is a request handler to validate service response. // ValidateResponseHandler is a request handler to validate service response.
func ValidateResponseHandler(r *Request) { var ValidateResponseHandler = request.NamedHandler{"core.ValidateResponseHandler", func(r *request.Request) {
if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 {
// this may be replaced by an UnmarshalError handler // this may be replaced by an UnmarshalError handler
r.Error = apierr.New("UnknownError", "unknown error", nil) r.Error = awserr.New("UnknownError", "unknown error", nil)
} }
} }}
// AfterRetryHandler performs final checks to determine if the request should // AfterRetryHandler performs final checks to determine if the request should
// be retried and how long to delay. // be retried and how long to delay.
func AfterRetryHandler(r *Request) { var AfterRetryHandler = request.NamedHandler{"core.AfterRetryHandler", func(r *request.Request) {
// If one of the other handlers already set the retry state // If one of the other handlers already set the retry state
// we don't want to override it based on the service's state // we don't want to override it based on the service's state
if !r.Retryable.IsSet() { if r.Retryable == nil {
r.Retryable.Set(r.Service.ShouldRetry(r)) r.Retryable = aws.Bool(r.ShouldRetry(r))
} }
if r.WillRetry() { if r.WillRetry() {
r.RetryDelay = r.Service.RetryRules(r) r.RetryDelay = r.RetryRules(r)
sleepDelay(r.RetryDelay) r.Service.Config.SleepDelay(r.RetryDelay)
// when the expired token exception occurs the credentials // when the expired token exception occurs the credentials
// need to be expired locally so that the next request to // need to be expired locally so that the next request to
// get credentials will trigger a credentials refresh. // get credentials will trigger a credentials refresh.
if r.Error != nil { if r.IsErrorExpired() {
if err, ok := r.Error.(awserr.Error); ok { r.Service.Config.Credentials.Expire()
if isCodeExpiredCreds(err.Code()) {
r.Config.Credentials.Expire()
// The credentials will need to be resigned with new credentials
r.signed = false
}
}
} }
r.RetryCount++ r.RetryCount++
r.Error = nil r.Error = nil
} }
} }}
var (
// ErrMissingRegion is an error that is returned if region configuration is
// not found.
ErrMissingRegion error = apierr.New("MissingRegion", "could not find region configuration", nil)
// ErrMissingEndpoint is an error that is returned if an endpoint cannot be
// resolved for a service.
ErrMissingEndpoint error = apierr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil)
)
// ValidateEndpointHandler is a request handler to validate a request had the // ValidateEndpointHandler is a request handler to validate a request had the
// appropriate Region and Endpoint set. Will set r.Error if the endpoint or // appropriate Region and Endpoint set. Will set r.Error if the endpoint or
// region is not valid. // region is not valid.
func ValidateEndpointHandler(r *Request) { var ValidateEndpointHandler = request.NamedHandler{"core.ValidateEndpointHandler", func(r *request.Request) {
if r.Service.SigningRegion == "" && r.Service.Config.Region == "" { if r.Service.SigningRegion == "" && aws.StringValue(r.Service.Config.Region) == "" {
r.Error = ErrMissingRegion r.Error = aws.ErrMissingRegion
} else if r.Service.Endpoint == "" { } else if r.Service.Endpoint == "" {
r.Error = ErrMissingEndpoint r.Error = aws.ErrMissingEndpoint
} }
} }}

View File

@@ -0,0 +1,107 @@
package corehandlers_test
import (
"fmt"
"net/http"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
)
func TestValidateEndpointHandler(t *testing.T) {
os.Clearenv()
svc := service.New(aws.NewConfig().WithRegion("us-west-2"))
svc.Handlers.Clear()
svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler)
req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
err := req.Build()
assert.NoError(t, err)
}
func TestValidateEndpointHandlerErrorRegion(t *testing.T) {
os.Clearenv()
svc := service.New(nil)
svc.Handlers.Clear()
svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler)
req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
err := req.Build()
assert.Error(t, err)
assert.Equal(t, aws.ErrMissingRegion, err)
}
type mockCredsProvider struct {
expired bool
retrieveCalled bool
}
func (m *mockCredsProvider) Retrieve() (credentials.Value, error) {
m.retrieveCalled = true
return credentials.Value{}, nil
}
func (m *mockCredsProvider) IsExpired() bool {
return m.expired
}
func TestAfterRetryRefreshCreds(t *testing.T) {
os.Clearenv()
credProvider := &mockCredsProvider{}
svc := service.New(&aws.Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: aws.Int(1)})
svc.Handlers.Clear()
svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) {
r.Error = awserr.New("UnknownError", "", nil)
r.HTTPResponse = &http.Response{StatusCode: 400}
})
svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) {
r.Error = awserr.New("ExpiredTokenException", "", nil)
})
svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)
assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
assert.False(t, credProvider.retrieveCalled)
req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
req.Send()
assert.True(t, svc.Config.Credentials.IsExpired())
assert.False(t, credProvider.retrieveCalled)
_, err := svc.Config.Credentials.Get()
assert.NoError(t, err)
assert.True(t, credProvider.retrieveCalled)
}
type testSendHandlerTransport struct{}
func (t *testSendHandlerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("mock error")
}
func TestSendHandlerError(t *testing.T) {
svc := service.New(&aws.Config{
HTTPClient: &http.Client{
Transport: &testSendHandlerTransport{},
},
})
svc.Handlers.Clear()
svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler)
r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
r.Send()
assert.Error(t, r.Error)
assert.NotNil(t, r.HTTPResponse)
}

View File

@@ -0,0 +1,144 @@
package corehandlers
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
)
// ValidateParameters is a request handler to validate the input parameters.
// Validating parameters only has meaning if done prior to the request being sent.
var ValidateParametersHandler = request.NamedHandler{"core.ValidateParametersHandler", func(r *request.Request) {
if r.ParamsFilled() {
v := validator{errors: []string{}}
v.validateAny(reflect.ValueOf(r.Params), "")
if count := len(v.errors); count > 0 {
format := "%d validation errors:\n- %s"
msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- "))
r.Error = awserr.New("InvalidParameter", msg, nil)
}
}
}}
// A validator validates values. Collects validations errors which occurs.
type validator struct {
errors []string
}
// validateAny will validate any struct, slice or map type. All validations
// are also performed recursively for nested types.
func (v *validator) validateAny(value reflect.Value, path string) {
value = reflect.Indirect(value)
if !value.IsValid() {
return
}
switch value.Kind() {
case reflect.Struct:
v.validateStruct(value, path)
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i))
}
case reflect.Map:
for _, n := range value.MapKeys() {
v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String()))
}
}
}
// validateStruct will validate the struct value's fields. If the structure has
// nested types those types will be validated also.
func (v *validator) validateStruct(value reflect.Value, path string) {
prefix := "."
if path == "" {
prefix = ""
}
for i := 0; i < value.Type().NumField(); i++ {
f := value.Type().Field(i)
if strings.ToLower(f.Name[0:1]) == f.Name[0:1] {
continue
}
fvalue := value.FieldByName(f.Name)
err := validateField(f, fvalue, validateFieldRequired, validateFieldMin)
if err != nil {
v.errors = append(v.errors, fmt.Sprintf("%s: %s", err.Error(), path+prefix+f.Name))
continue
}
v.validateAny(fvalue, path+prefix+f.Name)
}
}
type validatorFunc func(f reflect.StructField, fvalue reflect.Value) error
func validateField(f reflect.StructField, fvalue reflect.Value, funcs ...validatorFunc) error {
for _, fn := range funcs {
if err := fn(f, fvalue); err != nil {
return err
}
}
return nil
}
// Validates that a field has a valid value provided for required fields.
func validateFieldRequired(f reflect.StructField, fvalue reflect.Value) error {
if f.Tag.Get("required") == "" {
return nil
}
switch fvalue.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Map:
if fvalue.IsNil() {
return fmt.Errorf("missing required parameter")
}
default:
if !fvalue.IsValid() {
return fmt.Errorf("missing required parameter")
}
}
return nil
}
// Validates that if a value is provided for a field, that value must be at
// least a minimum length.
func validateFieldMin(f reflect.StructField, fvalue reflect.Value) error {
minStr := f.Tag.Get("min")
if minStr == "" {
return nil
}
min, _ := strconv.ParseInt(minStr, 10, 64)
kind := fvalue.Kind()
if kind == reflect.Ptr {
if fvalue.IsNil() {
return nil
}
fvalue = fvalue.Elem()
}
switch fvalue.Kind() {
case reflect.String:
if int64(fvalue.Len()) < min {
return fmt.Errorf("field too short, minimum length %d", min)
}
case reflect.Slice, reflect.Map:
if fvalue.IsNil() {
return nil
}
if int64(fvalue.Len()) < min {
return fmt.Errorf("field too short, minimum length %d", min)
}
// TODO min can also apply to number minimum value.
}
return nil
}

View File

@@ -0,0 +1,134 @@
package corehandlers_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/stretchr/testify/require"
)
var testSvc = func() *service.Service {
s := &service.Service{
ServiceInfo: serviceinfo.ServiceInfo{
Config: &aws.Config{},
ServiceName: "mock-service",
APIVersion: "2015-01-01",
},
}
return s
}()
type StructShape struct {
RequiredList []*ConditionalStructShape `required:"true"`
RequiredMap map[string]*ConditionalStructShape `required:"true"`
RequiredBool *bool `required:"true"`
OptionalStruct *ConditionalStructShape
hiddenParameter *string
metadataStructureShape
}
type metadataStructureShape struct {
SDKShapeTraits bool
}
type ConditionalStructShape struct {
Name *string `required:"true"`
SDKShapeTraits bool
}
func TestNoErrors(t *testing.T) {
input := &StructShape{
RequiredList: []*ConditionalStructShape{},
RequiredMap: map[string]*ConditionalStructShape{
"key1": {Name: aws.String("Name")},
"key2": {Name: aws.String("Name")},
},
RequiredBool: aws.Bool(true),
OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
}
req := testSvc.NewRequest(&request.Operation{}, input, nil)
corehandlers.ValidateParametersHandler.Fn(req)
require.NoError(t, req.Error)
}
func TestMissingRequiredParameters(t *testing.T) {
input := &StructShape{}
req := testSvc.NewRequest(&request.Operation{}, input, nil)
corehandlers.ValidateParametersHandler.Fn(req)
require.Error(t, req.Error)
assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message())
}
func TestNestedMissingRequiredParameters(t *testing.T) {
input := &StructShape{
RequiredList: []*ConditionalStructShape{{}},
RequiredMap: map[string]*ConditionalStructShape{
"key1": {Name: aws.String("Name")},
"key2": {},
},
RequiredBool: aws.Bool(true),
OptionalStruct: &ConditionalStructShape{},
}
req := testSvc.NewRequest(&request.Operation{}, input, nil)
corehandlers.ValidateParametersHandler.Fn(req)
require.Error(t, req.Error)
assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message())
}
type testInput struct {
StringField string `min:"5"`
PtrStrField *string `min:"2"`
ListField []string `min:"3"`
MapField map[string]string `min:"4"`
}
var testsFieldMin = []struct {
err awserr.Error
in testInput
}{
{
err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 5: StringField", nil),
in: testInput{StringField: "abcd"},
},
{
err: awserr.New("InvalidParameter", "2 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField", nil),
in: testInput{StringField: "abcd", ListField: []string{"a", "b"}},
},
{
err: awserr.New("InvalidParameter", "3 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField\n- field too short, minimum length 4: MapField", nil),
in: testInput{StringField: "abcd", ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}},
},
{
err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 2: PtrStrField", nil),
in: testInput{StringField: "abcde", PtrStrField: aws.String("v")},
},
{
err: nil,
in: testInput{StringField: "abcde", PtrStrField: aws.String("value"),
ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}},
},
}
func TestValidateFieldMinParameter(t *testing.T) {
for i, c := range testsFieldMin {
req := testSvc.NewRequest(&request.Operation{}, &c.in, nil)
corehandlers.ValidateParametersHandler.Fn(req)
require.Equal(t, c.err, req.Error, "%d case failed", i)
}
}

View File

@@ -1,13 +1,15 @@
package credentials package credentials
import ( import (
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
) )
var ( var (
// ErrNoValidProvidersFoundInChain Is returned when there are no valid // ErrNoValidProvidersFoundInChain Is returned when there are no valid
// providers in the ChainProvider. // providers in the ChainProvider.
ErrNoValidProvidersFoundInChain = apierr.New("NoCredentialProviders", "no valid providers in chain", nil) //
// @readonly
ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", "no valid providers in chain", nil)
) )
// A ChainProvider will search for a provider which returns credentials // A ChainProvider will search for a provider which returns credentials
@@ -36,7 +38,9 @@ var (
// &EnvProvider{}, // &EnvProvider{},
// &EC2RoleProvider{}, // &EC2RoleProvider{},
// }) // })
// creds.Retrieve() //
// // Usage of ChainCredentials with aws.Config
// svc := ec2.New(&aws.Config{Credentials: creds})
// //
type ChainProvider struct { type ChainProvider struct {
Providers []Provider Providers []Provider

View File

@@ -3,15 +3,15 @@ package credentials
import ( import (
"testing" "testing"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestChainProviderGet(t *testing.T) { func TestChainProviderGet(t *testing.T) {
p := &ChainProvider{ p := &ChainProvider{
Providers: []Provider{ Providers: []Provider{
&stubProvider{err: apierr.New("FirstError", "first provider error", nil)}, &stubProvider{err: awserr.New("FirstError", "first provider error", nil)},
&stubProvider{err: apierr.New("SecondError", "second provider error", nil)}, &stubProvider{err: awserr.New("SecondError", "second provider error", nil)},
&stubProvider{ &stubProvider{
creds: Value{ creds: Value{
AccessKeyID: "AKID", AccessKeyID: "AKID",
@@ -62,8 +62,8 @@ func TestChainProviderWithNoProvider(t *testing.T) {
func TestChainProviderWithNoValidProvider(t *testing.T) { func TestChainProviderWithNoValidProvider(t *testing.T) {
p := &ChainProvider{ p := &ChainProvider{
Providers: []Provider{ Providers: []Provider{
&stubProvider{err: apierr.New("FirstError", "first provider error", nil)}, &stubProvider{err: awserr.New("FirstError", "first provider error", nil)},
&stubProvider{err: apierr.New("SecondError", "second provider error", nil)}, &stubProvider{err: awserr.New("SecondError", "second provider error", nil)},
}, },
} }

View File

@@ -63,6 +63,7 @@ import (
// svc := s3.New(&aws.Config{Credentials: AnonymousCredentials}) // svc := s3.New(&aws.Config{Credentials: AnonymousCredentials})
// // Access public S3 buckets. // // Access public S3 buckets.
// //
// @readonly
var AnonymousCredentials = NewStaticCredentials("", "", "") var AnonymousCredentials = NewStaticCredentials("", "", "")
// A Value is the AWS credentials value for individual credential fields. // A Value is the AWS credentials value for individual credential fields.
@@ -93,6 +94,50 @@ type Provider interface {
IsExpired() bool IsExpired() bool
} }
// A Expiry provides shared expiration logic to be used by credentials
// providers to implement expiry functionality.
//
// The best method to use this struct is as an anonymous field within the
// provider's struct.
//
// Example:
// type EC2RoleProvider struct {
// Expiry
// ...
// }
type Expiry struct {
// The date/time when to expire on
expiration time.Time
// If set will be used by IsExpired to determine the current time.
// Defaults to time.Now if CurrentTime is not set. Available for testing
// to be able to mock out the current time.
CurrentTime func() time.Time
}
// SetExpiration sets the expiration IsExpired will check when called.
//
// If window is greater than 0 the expiration time will be reduced by the
// window value.
//
// Using a window is helpful to trigger credentials to expire sooner than
// the expiration time given to ensure no requests are made with expired
// tokens.
func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) {
e.expiration = expiration
if window > 0 {
e.expiration = e.expiration.Add(-window)
}
}
// IsExpired returns if the credentials are expired.
func (e *Expiry) IsExpired() bool {
if e.CurrentTime == nil {
e.CurrentTime = time.Now
}
return e.expiration.Before(e.CurrentTime())
}
// A Credentials provides synchronous safe retrieval of AWS credentials Value. // A Credentials provides synchronous safe retrieval of AWS credentials Value.
// Credentials will cache the credentials value until they expire. Once the value // Credentials will cache the credentials value until they expire. Once the value
// expires the next Get will attempt to retrieve valid credentials. // expires the next Get will attempt to retrieve valid credentials.
@@ -173,6 +218,3 @@ func (c *Credentials) IsExpired() bool {
func (c *Credentials) isExpired() bool { func (c *Credentials) isExpired() bool {
return c.forceRefresh || c.provider.IsExpired() return c.forceRefresh || c.provider.IsExpired()
} }
// Provide a stub-able time.Now for unit tests so expiry can be tested.
var currentTime = time.Now

View File

@@ -4,7 +4,6 @@ import (
"testing" "testing"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -40,7 +39,7 @@ func TestCredentialsGet(t *testing.T) {
} }
func TestCredentialsGetWithError(t *testing.T) { func TestCredentialsGetWithError(t *testing.T) {
c := NewCredentials(&stubProvider{err: apierr.New("provider error", "", nil), expired: true}) c := NewCredentials(&stubProvider{err: awserr.New("provider error", "", nil), expired: true})
_, err := c.Get() _, err := c.Get()
assert.Equal(t, "provider error", err.(awserr.Error).Code(), "Expected provider error") assert.Equal(t, "provider error", err.(awserr.Error).Code(), "Expected provider error")

View File

@@ -1,114 +0,0 @@
package credentials
import (
"fmt"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func initTestServer(expireOn string) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/" {
fmt.Fprintln(w, "/creds")
} else {
fmt.Fprintf(w, `{
"AccessKeyId" : "accessKey",
"SecretAccessKey" : "secret",
"Token" : "token",
"Expiration" : "%s"
}`, expireOn)
}
}))
return server
}
func TestEC2RoleProvider(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z")
defer server.Close()
p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL}
creds, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match")
assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match")
assert.Equal(t, "token", creds.SessionToken, "Expect session token to match")
}
func TestEC2RoleProviderIsExpired(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z")
defer server.Close()
p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL}
defer func() {
currentTime = time.Now
}()
currentTime = func() time.Time {
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")
_, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")
currentTime = func() time.Time {
return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z")
defer server.Close()
p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL, ExpiryWindow: time.Hour * 1}
defer func() {
currentTime = time.Now
}()
currentTime = func() time.Time {
return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")
_, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")
currentTime = func() time.Time {
return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
func BenchmarkEC2RoleProvider(b *testing.B) {
server := initTestServer("2014-12-16T01:51:37Z")
defer server.Close()
p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL}
_, err := p.Retrieve()
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := p.Retrieve()
if err != nil {
b.Fatal(err)
}
}
})
}

View File

@@ -1,24 +1,25 @@
package credentials package ec2rolecreds
import ( import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "path"
"strings"
"time" "time"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
) )
const metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if // A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if
// those credentials are expired. // those credentials are expired.
// //
// Example how to configure the EC2RoleProvider with custom http Client, Endpoint // Example how to configure the EC2RoleProvider with custom http Client, Endpoint
// or ExpiryWindow // or ExpiryWindow
// //
// p := &credentials.EC2RoleProvider{ // p := &ec2rolecreds.EC2RoleProvider{
// // Pass in a custom timeout to be used when requesting // // Pass in a custom timeout to be used when requesting
// // IAM EC2 Role credentials. // // IAM EC2 Role credentials.
// Client: &http.Client{ // Client: &http.Client{
@@ -31,13 +32,11 @@ const metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam
// // specified the credentials will be expired early // // specified the credentials will be expired early
// ExpiryWindow: 0, // ExpiryWindow: 0,
// } // }
//
type EC2RoleProvider struct { type EC2RoleProvider struct {
// Endpoint must be fully quantified URL credentials.Expiry
Endpoint string
// HTTP client to use when connecting to EC2 service // EC2Metadata client to use when connecting to EC2 metadata service
Client *http.Client Client *ec2metadata.Client
// ExpiryWindow will allow the credentials to trigger refreshing prior to // ExpiryWindow will allow the credentials to trigger refreshing prior to
// the credentials actually expiring. This is beneficial so race conditions // the credentials actually expiring. This is beneficial so race conditions
@@ -49,12 +48,9 @@ type EC2RoleProvider struct {
// //
// If ExpiryWindow is 0 or less it will be ignored. // If ExpiryWindow is 0 or less it will be ignored.
ExpiryWindow time.Duration ExpiryWindow time.Duration
// The date/time at which the credentials expire.
expiresOn time.Time
} }
// NewEC2RoleCredentials returns a pointer to a new Credentials object // NewCredentials returns a pointer to a new Credentials object
// wrapping the EC2RoleProvider. // wrapping the EC2RoleProvider.
// //
// Takes a custom http.Client which can be configured for custom handling of // Takes a custom http.Client which can be configured for custom handling of
@@ -66,9 +62,8 @@ type EC2RoleProvider struct {
// Window is the expiry window that will be subtracted from the expiry returned // Window is the expiry window that will be subtracted from the expiry returned
// by the role credential request. This is done so that the credentials will // by the role credential request. This is done so that the credentials will
// expire sooner than their actual lifespan. // expire sooner than their actual lifespan.
func NewEC2RoleCredentials(client *http.Client, endpoint string, window time.Duration) *Credentials { func NewCredentials(client *ec2metadata.Client, window time.Duration) *credentials.Credentials {
return NewCredentials(&EC2RoleProvider{ return credentials.NewCredentials(&EC2RoleProvider{
Endpoint: endpoint,
Client: client, Client: client,
ExpiryWindow: window, ExpiryWindow: window,
}) })
@@ -77,73 +72,67 @@ func NewEC2RoleCredentials(client *http.Client, endpoint string, window time.Dur
// Retrieve retrieves credentials from the EC2 service. // Retrieve retrieves credentials from the EC2 service.
// Error will be returned if the request fails, or unable to extract // Error will be returned if the request fails, or unable to extract
// the desired credentials. // the desired credentials.
func (m *EC2RoleProvider) Retrieve() (Value, error) { func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) {
if m.Client == nil { if m.Client == nil {
m.Client = http.DefaultClient m.Client = ec2metadata.New(nil)
}
if m.Endpoint == "" {
m.Endpoint = metadataCredentialsEndpoint
} }
credsList, err := requestCredList(m.Client, m.Endpoint) credsList, err := requestCredList(m.Client)
if err != nil { if err != nil {
return Value{}, err return credentials.Value{}, err
} }
if len(credsList) == 0 { if len(credsList) == 0 {
return Value{}, apierr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) return credentials.Value{}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil)
} }
credsName := credsList[0] credsName := credsList[0]
roleCreds, err := requestCred(m.Client, m.Endpoint, credsName) roleCreds, err := requestCred(m.Client, credsName)
if err != nil { if err != nil {
return Value{}, err return credentials.Value{}, err
} }
m.expiresOn = roleCreds.Expiration m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow)
if m.ExpiryWindow > 0 {
// Offset based on expiry window if set.
m.expiresOn = m.expiresOn.Add(-m.ExpiryWindow)
}
return Value{ return credentials.Value{
AccessKeyID: roleCreds.AccessKeyID, AccessKeyID: roleCreds.AccessKeyID,
SecretAccessKey: roleCreds.SecretAccessKey, SecretAccessKey: roleCreds.SecretAccessKey,
SessionToken: roleCreds.Token, SessionToken: roleCreds.Token,
}, nil }, nil
} }
// IsExpired returns if the credentials are expired.
func (m *EC2RoleProvider) IsExpired() bool {
return m.expiresOn.Before(currentTime())
}
// A ec2RoleCredRespBody provides the shape for deserializing credential // A ec2RoleCredRespBody provides the shape for deserializing credential
// request responses. // request responses.
type ec2RoleCredRespBody struct { type ec2RoleCredRespBody struct {
// Success State
Expiration time.Time Expiration time.Time
AccessKeyID string AccessKeyID string
SecretAccessKey string SecretAccessKey string
Token string Token string
// Error state
Code string
Message string
} }
const iamSecurityCredsPath = "/iam/security-credentials"
// requestCredList requests a list of credentials from the EC2 service. // requestCredList requests a list of credentials from the EC2 service.
// If there are no credentials, or there is an error making or receiving the request // If there are no credentials, or there is an error making or receiving the request
func requestCredList(client *http.Client, endpoint string) ([]string, error) { func requestCredList(client *ec2metadata.Client) ([]string, error) {
resp, err := client.Get(endpoint) resp, err := client.GetMetadata(iamSecurityCredsPath)
if err != nil { if err != nil {
return nil, apierr.New("ListEC2Role", "failed to list EC2 Roles", err) return nil, awserr.New("EC2RoleRequestError", "failed to list EC2 Roles", err)
} }
defer resp.Body.Close()
credsList := []string{} credsList := []string{}
s := bufio.NewScanner(resp.Body) s := bufio.NewScanner(strings.NewReader(resp))
for s.Scan() { for s.Scan() {
credsList = append(credsList, s.Text()) credsList = append(credsList, s.Text())
} }
if err := s.Err(); err != nil { if err := s.Err(); err != nil {
return nil, apierr.New("ReadEC2Role", "failed to read list of EC2 Roles", err) return nil, awserr.New("SerializationError", "failed to read list of EC2 Roles", err)
} }
return credsList, nil return credsList, nil
@@ -153,21 +142,27 @@ func requestCredList(client *http.Client, endpoint string) ([]string, error) {
// //
// If the credentials cannot be found, or there is an error reading the response // If the credentials cannot be found, or there is an error reading the response
// and error will be returned. // and error will be returned.
func requestCred(client *http.Client, endpoint, credsName string) (*ec2RoleCredRespBody, error) { func requestCred(client *ec2metadata.Client, credsName string) (ec2RoleCredRespBody, error) {
resp, err := client.Get(endpoint + credsName) resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName))
if err != nil { if err != nil {
return nil, apierr.New("GetEC2RoleCredentials", return ec2RoleCredRespBody{},
awserr.New("EC2RoleRequestError",
fmt.Sprintf("failed to get %s EC2 Role credentials", credsName), fmt.Sprintf("failed to get %s EC2 Role credentials", credsName),
err) err)
} }
defer resp.Body.Close()
respCreds := &ec2RoleCredRespBody{} respCreds := ec2RoleCredRespBody{}
if err := json.NewDecoder(resp.Body).Decode(respCreds); err != nil { if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil {
return nil, apierr.New("DecodeEC2RoleCredentials", return ec2RoleCredRespBody{},
awserr.New("SerializationError",
fmt.Sprintf("failed to decode %s EC2 Role credentials", credsName), fmt.Sprintf("failed to decode %s EC2 Role credentials", credsName),
err) err)
} }
if respCreds.Code != "Success" {
// If an error code was returned something failed requesting the role.
return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil)
}
return respCreds, nil return respCreds, nil
} }

View File

@@ -0,0 +1,161 @@
package ec2rolecreds_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
)
const credsRespTmpl = `{
"Code": "Success",
"Type": "AWS-HMAC",
"AccessKeyId" : "accessKey",
"SecretAccessKey" : "secret",
"Token" : "token",
"Expiration" : "%s",
"LastUpdated" : "2009-11-23T0:00:00Z"
}`
const credsFailRespTmpl = `{
"Code": "ErrorCode",
"Message": "ErrorMsg",
"LastUpdated": "2009-11-23T0:00:00Z"
}`
func initTestServer(expireOn string, failAssume bool) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/latest/meta-data/iam/security-credentials" {
fmt.Fprintln(w, "RoleName")
} else if r.URL.Path == "/latest/meta-data/iam/security-credentials/RoleName" {
if failAssume {
fmt.Fprintf(w, credsFailRespTmpl)
} else {
fmt.Fprintf(w, credsRespTmpl, expireOn)
}
} else {
http.Error(w, "bad request", http.StatusBadRequest)
}
}))
return server
}
func TestEC2RoleProvider(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z", false)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
creds, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match")
assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match")
assert.Equal(t, "token", creds.SessionToken, "Expect session token to match")
}
func TestEC2RoleProviderFailAssume(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z", true)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
creds, err := p.Retrieve()
assert.Error(t, err, "Expect error")
e := err.(awserr.Error)
assert.Equal(t, "ErrorCode", e.Code())
assert.Equal(t, "ErrorMsg", e.Message())
assert.Nil(t, e.OrigErr())
assert.Equal(t, "", creds.AccessKeyID, "Expect access key ID to match")
assert.Equal(t, "", creds.SecretAccessKey, "Expect secret access key to match")
assert.Equal(t, "", creds.SessionToken, "Expect session token to match")
}
func TestEC2RoleProviderIsExpired(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z", false)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")
_, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")
p.CurrentTime = func() time.Time {
return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) {
server := initTestServer("2014-12-16T01:51:37Z", false)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
ExpiryWindow: time.Hour * 1,
}
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired before retrieve.")
_, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.")
p.CurrentTime = func() time.Time {
return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC)
}
assert.True(t, p.IsExpired(), "Expect creds to be expired.")
}
func BenchmarkEC2RoleProvider(b *testing.B) {
server := initTestServer("2014-12-16T01:51:37Z", false)
defer server.Close()
p := &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")}),
}
_, err := p.Retrieve()
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := p.Retrieve()
if err != nil {
b.Fatal(err)
}
}
})
}

View File

@@ -3,24 +3,30 @@ package credentials
import ( import (
"os" "os"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
) )
var ( var (
// ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
// found in the process's environment. // found in the process's environment.
ErrAccessKeyIDNotFound = apierr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) //
// @readonly
ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil)
// ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
// can't be found in the process's environment. // can't be found in the process's environment.
ErrSecretAccessKeyNotFound = apierr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) //
// @readonly
ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil)
) )
// A EnvProvider retrieves credentials from the environment variables of the // A EnvProvider retrieves credentials from the environment variables of the
// running process. Environment credentials never expire. // running process. Environment credentials never expire.
// //
// Environment variables used: // Environment variables used:
// - Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY //
// - Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY // * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
type EnvProvider struct { type EnvProvider struct {
retrieved bool retrieved bool
} }

View File

@@ -7,12 +7,14 @@ import (
"github.com/vaughan0/go-ini" "github.com/vaughan0/go-ini"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
) )
var ( var (
// ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found.
ErrSharedCredentialsHomeNotFound = apierr.New("UserHomeNotFound", "user home directory not found.", nil) //
// @readonly
ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil)
) )
// A SharedCredentialsProvider retrieves credentials from the current user's home // A SharedCredentialsProvider retrieves credentials from the current user's home
@@ -20,8 +22,12 @@ var (
// //
// Profile ini file example: $HOME/.aws/credentials // Profile ini file example: $HOME/.aws/credentials
type SharedCredentialsProvider struct { type SharedCredentialsProvider struct {
// Path to the shared credentials file. If empty will default to current user's // Path to the shared credentials file.
// home directory. //
// If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the
// env value is empty will default to current user's home directory.
// Linux/OSX: "$HOME/.aws/credentials"
// Windows: "%USERPROFILE%\.aws\credentials"
Filename string Filename string
// AWS Profile to extract credentials from the shared credentials file. If empty // AWS Profile to extract credentials from the shared credentials file. If empty
@@ -72,20 +78,20 @@ func (p *SharedCredentialsProvider) IsExpired() bool {
func loadProfile(filename, profile string) (Value, error) { func loadProfile(filename, profile string) (Value, error) {
config, err := ini.LoadFile(filename) config, err := ini.LoadFile(filename)
if err != nil { if err != nil {
return Value{}, apierr.New("SharedCredsLoad", "failed to load shared credentials file", err) return Value{}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err)
} }
iniProfile := config.Section(profile) iniProfile := config.Section(profile)
id, ok := iniProfile["aws_access_key_id"] id, ok := iniProfile["aws_access_key_id"]
if !ok { if !ok {
return Value{}, apierr.New("SharedCredsAccessKey", return Value{}, awserr.New("SharedCredsAccessKey",
fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename),
nil) nil)
} }
secret, ok := iniProfile["aws_secret_access_key"] secret, ok := iniProfile["aws_secret_access_key"]
if !ok { if !ok {
return Value{}, apierr.New("SharedCredsSecret", return Value{}, awserr.New("SharedCredsSecret",
fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename),
nil) nil)
} }
@@ -104,6 +110,10 @@ func loadProfile(filename, profile string) (Value, error) {
// Will return an error if the user's home directory path cannot be found. // Will return an error if the user's home directory path cannot be found.
func (p *SharedCredentialsProvider) filename() (string, error) { func (p *SharedCredentialsProvider) filename() (string, error) {
if p.Filename == "" { if p.Filename == "" {
if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); p.Filename != "" {
return p.Filename, nil
}
homeDir := os.Getenv("HOME") // *nix homeDir := os.Getenv("HOME") // *nix
if homeDir == "" { // Windows if homeDir == "" { // Windows
homeDir = os.Getenv("USERPROFILE") homeDir = os.Getenv("USERPROFILE")

View File

@@ -31,6 +31,19 @@ func TestSharedCredentialsProviderIsExpired(t *testing.T) {
assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve") assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve")
} }
func TestSharedCredentialsProviderWithAWS_SHARED_CREDENTIALS_FILE(t *testing.T) {
os.Clearenv()
os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "example.ini")
p := SharedCredentialsProvider{}
creds, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.Equal(t, "accessKey", creds.AccessKeyID, "Expect access key ID to match")
assert.Equal(t, "secret", creds.SecretAccessKey, "Expect secret access key to match")
assert.Equal(t, "token", creds.SessionToken, "Expect session token to match")
}
func TestSharedCredentialsProviderWithAWS_PROFILE(t *testing.T) { func TestSharedCredentialsProviderWithAWS_PROFILE(t *testing.T) {
os.Clearenv() os.Clearenv()
os.Setenv("AWS_PROFILE", "no_token") os.Setenv("AWS_PROFILE", "no_token")
@@ -66,12 +79,10 @@ func BenchmarkSharedCredentialsProvider(b *testing.B) {
} }
b.ResetTimer() b.ResetTimer()
b.RunParallel(func(pb *testing.PB) { for i := 0; i < b.N; i++ {
for pb.Next() {
_, err := p.Retrieve() _, err := p.Retrieve()
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
} }
})
} }

View File

@@ -1,12 +1,14 @@
package credentials package credentials
import ( import (
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
) )
var ( var (
// ErrStaticCredentialsEmpty is emitted when static credentials are empty. // ErrStaticCredentialsEmpty is emitted when static credentials are empty.
ErrStaticCredentialsEmpty = apierr.New("EmptyStaticCreds", "static credentials are empty", nil) //
// @readonly
ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil)
) )
// A StaticProvider is a set of credentials which are set pragmatically, // A StaticProvider is a set of credentials which are set pragmatically,

View File

@@ -0,0 +1,125 @@
// Package stscreds are credential Providers to retrieve STS AWS credentials.
//
// STS provides multiple ways to retrieve credentials which can be used when making
// future AWS service API operation calls.
package stscreds
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/service/sts"
)
// AssumeRoler represents the minimal subset of the STS client API used by this provider.
type AssumeRoler interface {
AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error)
}
// AssumeRoleProvider retrieves temporary credentials from the STS service, and
// keeps track of their expiration time. This provider must be used explicitly,
// as it is not included in the credentials chain.
//
// Example how to configure a service to use this provider:
//
// config := &aws.Config{
// Credentials: stscreds.NewCredentials(nil, "arn-of-the-role-to-assume", 10*time.Second),
// })
// // Use config for creating your AWS service.
//
// Example how to obtain customised credentials:
//
// provider := &stscreds.Provider{
// // Extend the duration to 1 hour.
// Duration: time.Hour,
// // Custom role name.
// RoleSessionName: "custom-session-name",
// }
// creds := credentials.NewCredentials(provider)
//
type AssumeRoleProvider struct {
credentials.Expiry
// Custom STS client. If not set the default STS client will be used.
Client AssumeRoler
// Role to be assumed.
RoleARN string
// Session name, if you wish to reuse the credentials elsewhere.
RoleSessionName string
// Expiry duration of the STS credentials. Defaults to 15 minutes if not set.
Duration time.Duration
// Optional ExternalID to pass along, defaults to nil if not set.
ExternalID *string
// ExpiryWindow will allow the credentials to trigger refreshing prior to
// the credentials actually expiring. This is beneficial so race conditions
// with expiring credentials do not cause request to fail unexpectedly
// due to ExpiredTokenException exceptions.
//
// So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
// 10 seconds before the credentials are actually expired.
//
// If ExpiryWindow is 0 or less it will be ignored.
ExpiryWindow time.Duration
}
// NewCredentials returns a pointer to a new Credentials object wrapping the
// AssumeRoleProvider. The credentials will expire every 15 minutes and the
// role will be named after a nanosecond timestamp of this operation.
//
// The sts and roleARN parameters are used for building the "AssumeRole" call.
// Pass nil as sts to use the default client.
//
// Window is the expiry window that will be subtracted from the expiry returned
// by the role credential request. This is done so that the credentials will
// expire sooner than their actual lifespan.
func NewCredentials(client AssumeRoler, roleARN string, window time.Duration) *credentials.Credentials {
return credentials.NewCredentials(&AssumeRoleProvider{
Client: client,
RoleARN: roleARN,
ExpiryWindow: window,
})
}
// Retrieve generates a new set of temporary credentials using STS.
func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {
// Apply defaults where parameters are not set.
if p.Client == nil {
p.Client = sts.New(nil)
}
if p.RoleSessionName == "" {
// Try to work out a role name that will hopefully end up unique.
p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
}
if p.Duration == 0 {
// Expire as often as AWS permits.
p.Duration = 15 * time.Minute
}
roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{
DurationSeconds: aws.Int64(int64(p.Duration / time.Second)),
RoleArn: aws.String(p.RoleARN),
RoleSessionName: aws.String(p.RoleSessionName),
ExternalId: p.ExternalID,
})
if err != nil {
return credentials.Value{}, err
}
// We will proactively generate new credentials before they expire.
p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)
return credentials.Value{
AccessKeyID: *roleOutput.Credentials.AccessKeyId,
SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
SessionToken: *roleOutput.Credentials.SessionToken,
}, nil
}

View File

@@ -0,0 +1,59 @@
package stscreds
import (
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/stretchr/testify/assert"
)
type stubSTS struct {
}
func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) {
expiry := time.Now().Add(60 * time.Minute)
return &sts.AssumeRoleOutput{
Credentials: &sts.Credentials{
// Just reflect the role arn to the provider.
AccessKeyId: input.RoleArn,
SecretAccessKey: aws.String("assumedSecretAccessKey"),
SessionToken: aws.String("assumedSessionToken"),
Expiration: &expiry,
},
}, nil
}
func TestAssumeRoleProvider(t *testing.T) {
stub := &stubSTS{}
p := &AssumeRoleProvider{
Client: stub,
RoleARN: "roleARN",
}
creds, err := p.Retrieve()
assert.Nil(t, err, "Expect no error")
assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN")
assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match")
assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match")
}
func BenchmarkAssumeRoleProvider(b *testing.B) {
stub := &stubSTS{}
p := &AssumeRoleProvider{
Client: stub,
RoleARN: "roleARN",
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := p.Retrieve()
if err != nil {
b.Fatal(err)
}
}
})
}

View File

@@ -0,0 +1,39 @@
package defaults
import (
"net/http"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
)
// DefaultChainCredentials is a Credentials which will find the first available
// credentials Value from the list of Providers.
//
// This should be used in the default case. Once the type of credentials are
// known switching to the specific Credentials will be more efficient.
var DefaultChainCredentials = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
})
// DefaultConfig is the default all service configuration will be based off of.
// By default, all clients use this structure for initialization options unless
// a custom configuration object is passed in.
//
// You may modify this global structure to change all default configuration
// in the SDK. Note that configuration options are copied by value, so any
// modifications must happen before constructing a client.
var DefaultConfig = aws.NewConfig().
WithCredentials(DefaultChainCredentials).
WithRegion(os.Getenv("AWS_REGION")).
WithHTTPClient(http.DefaultClient).
WithMaxRetries(aws.DefaultRetries).
WithLogger(aws.NewDefaultLogger()).
WithLogLevel(aws.LogOff).
WithSleepDelay(time.Sleep)

View File

@@ -0,0 +1,43 @@
package ec2metadata
import (
"path"
"github.com/aws/aws-sdk-go/aws/request"
)
// GetMetadata uses the path provided to request
func (c *Client) GetMetadata(p string) (string, error) {
op := &request.Operation{
Name: "GetMetadata",
HTTPMethod: "GET",
HTTPPath: path.Join("/", "meta-data", p),
}
output := &metadataOutput{}
req := request.New(c.Service.ServiceInfo, c.Service.Handlers, c.Service.Retryer, op, nil, output)
return output.Content, req.Send()
}
// Region returns the region the instance is running in.
func (c *Client) Region() (string, error) {
resp, err := c.GetMetadata("placement/availability-zone")
if err != nil {
return "", err
}
// returns region without the suffix. Eg: us-west-2a becomes us-west-2
return resp[:len(resp)-1], nil
}
// Available returns if the application has access to the EC2 Metadata service.
// Can be used to determine if application is running within an EC2 Instance and
// the metadata service is available.
func (c *Client) Available() bool {
if _, err := c.GetMetadata("instance-id"); err != nil {
return false
}
return true
}

View File

@@ -0,0 +1,100 @@
package ec2metadata_test
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/request"
)
func initTestServer(path string, resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != path {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Write([]byte(resp))
}))
}
func TestEndpoint(t *testing.T) {
c := ec2metadata.New(&ec2metadata.Config{})
op := &request.Operation{
Name: "GetMetadata",
HTTPMethod: "GET",
HTTPPath: path.Join("/", "meta-data", "testpath"),
}
req := c.Service.NewRequest(op, nil, nil)
assert.Equal(t, "http://169.254.169.254/latest", req.Service.Endpoint)
assert.Equal(t, "http://169.254.169.254/latest/meta-data/testpath", req.HTTPRequest.URL.String())
}
func TestGetMetadata(t *testing.T) {
server := initTestServer(
"/latest/meta-data/some/path",
"success", // real response includes suffix
)
defer server.Close()
c := ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")})
resp, err := c.GetMetadata("some/path")
assert.NoError(t, err)
assert.Equal(t, "success", resp)
}
func TestGetRegion(t *testing.T) {
server := initTestServer(
"/latest/meta-data/placement/availability-zone",
"us-west-2a", // real response includes suffix
)
defer server.Close()
c := ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")})
region, err := c.Region()
assert.NoError(t, err)
assert.Equal(t, "us-west-2", region)
}
func TestMetadataAvailable(t *testing.T) {
server := initTestServer(
"/latest/meta-data/instance-id",
"instance-id",
)
defer server.Close()
c := ec2metadata.New(&ec2metadata.Config{Endpoint: aws.String(server.URL + "/latest")})
available := c.Available()
assert.True(t, available)
}
func TestMetadataNotAvailable(t *testing.T) {
c := ec2metadata.New(nil)
c.Handlers.Send.Clear()
c.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &http.Response{
StatusCode: int(0),
Status: http.StatusText(int(0)),
Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
}
r.Error = awserr.New("RequestError", "send request failed", nil)
r.Retryable = aws.Bool(true) // network errors are retryable
})
available := c.Available()
assert.False(t, available)
}

View File

@@ -0,0 +1,135 @@
package ec2metadata
import (
"io/ioutil"
"net/http"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
)
// DefaultRetries states the default number of times the service client will
// attempt to retry a failed request before failing.
const DefaultRetries = 3
// A Config provides the configuration for the EC2 Metadata service.
type Config struct {
// An optional endpoint URL (hostname only or fully qualified URI)
// that overrides the default service endpoint for a client. Set this
// to nil, or `""` to use the default service endpoint.
Endpoint *string
// The HTTP client to use when sending requests. Defaults to
// `http.DefaultClient`.
HTTPClient *http.Client
// An integer value representing the logging level. The default log level
// is zero (LogOff), which represents no logging. To enable logging set
// to a LogLevel Value.
Logger aws.Logger
// The logger writer interface to write logging messages to. Defaults to
// standard out.
LogLevel *aws.LogLevelType
// The maximum number of times that a request will be retried for failures.
// Defaults to DefaultRetries for the number of retries to be performed
// per request.
MaxRetries *int
}
// A Client is an EC2 Metadata service Client.
type Client struct {
*service.Service
}
// New creates a new instance of the EC2 Metadata service client.
//
// In the general use case the configuration for this service client should not
// be needed and `nil` can be provided. Configuration is only needed if the
// `ec2metadata.Config` defaults need to be overridden. Eg. Setting LogLevel.
//
// @note This configuration will NOT be merged with the default AWS service
// client configuration `defaults.DefaultConfig`. Due to circular dependencies
// with the defaults package and credentials EC2 Role Provider.
func New(config *Config) *Client {
service := &service.Service{
ServiceInfo: serviceinfo.ServiceInfo{
Config: copyConfig(config),
ServiceName: "Client",
Endpoint: "http://169.254.169.254/latest",
APIVersion: "latest",
},
}
service.Initialize()
service.Handlers.Unmarshal.PushBack(unmarshalHandler)
service.Handlers.UnmarshalError.PushBack(unmarshalError)
service.Handlers.Validate.Clear()
service.Handlers.Validate.PushBack(validateEndpointHandler)
return &Client{service}
}
func copyConfig(config *Config) *aws.Config {
if config == nil {
config = &Config{}
}
c := &aws.Config{
Credentials: credentials.AnonymousCredentials,
Endpoint: config.Endpoint,
HTTPClient: config.HTTPClient,
Logger: config.Logger,
LogLevel: config.LogLevel,
MaxRetries: config.MaxRetries,
}
if c.HTTPClient == nil {
c.HTTPClient = http.DefaultClient
}
if c.Logger == nil {
c.Logger = aws.NewDefaultLogger()
}
if c.LogLevel == nil {
c.LogLevel = aws.LogLevel(aws.LogOff)
}
if c.MaxRetries == nil {
c.MaxRetries = aws.Int(DefaultRetries)
}
return c
}
type metadataOutput struct {
Content string
}
func unmarshalHandler(r *request.Request) {
defer r.HTTPResponse.Body.Close()
b, err := ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil {
r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata respose", err)
}
data := r.Data.(*metadataOutput)
data.Content = string(b)
}
func unmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close()
_, err := ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil {
r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err)
}
// TODO extract the error...
}
func validateEndpointHandler(r *request.Request) {
if r.Service.Endpoint == "" {
r.Error = aws.ErrMissingEndpoint
}
}

View File

@@ -0,0 +1,17 @@
package aws
import "github.com/aws/aws-sdk-go/aws/awserr"
var (
// ErrMissingRegion is an error that is returned if region configuration is
// not found.
//
// @readonly
ErrMissingRegion error = awserr.New("MissingRegion", "could not find region configuration", nil)
// ErrMissingEndpoint is an error that is returned if an endpoint cannot be
// resolved for a service.
//
// @readonly
ErrMissingEndpoint error = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil)
)

View File

@@ -1,81 +0,0 @@
package aws
import (
"net/http"
"os"
"testing"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/internal/apierr"
"github.com/stretchr/testify/assert"
)
func TestValidateEndpointHandler(t *testing.T) {
os.Clearenv()
svc := NewService(&Config{Region: "us-west-2"})
svc.Handlers.Clear()
svc.Handlers.Validate.PushBack(ValidateEndpointHandler)
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
err := req.Build()
assert.NoError(t, err)
}
func TestValidateEndpointHandlerErrorRegion(t *testing.T) {
os.Clearenv()
svc := NewService(nil)
svc.Handlers.Clear()
svc.Handlers.Validate.PushBack(ValidateEndpointHandler)
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
err := req.Build()
assert.Error(t, err)
assert.Equal(t, ErrMissingRegion, err)
}
type mockCredsProvider struct {
expired bool
retreiveCalled bool
}
func (m *mockCredsProvider) Retrieve() (credentials.Value, error) {
m.retreiveCalled = true
return credentials.Value{}, nil
}
func (m *mockCredsProvider) IsExpired() bool {
return m.expired
}
func TestAfterRetryRefreshCreds(t *testing.T) {
os.Clearenv()
credProvider := &mockCredsProvider{}
svc := NewService(&Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: 1})
svc.Handlers.Clear()
svc.Handlers.ValidateResponse.PushBack(func(r *Request) {
r.Error = apierr.New("UnknownError", "", nil)
r.HTTPResponse = &http.Response{StatusCode: 400}
})
svc.Handlers.UnmarshalError.PushBack(func(r *Request) {
r.Error = apierr.New("ExpiredTokenException", "", nil)
})
svc.Handlers.AfterRetry.PushBack(func(r *Request) {
AfterRetryHandler(r)
})
assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
assert.False(t, credProvider.retreiveCalled)
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
req.Send()
assert.True(t, svc.Config.Credentials.IsExpired())
assert.False(t, credProvider.retreiveCalled)
_, err := svc.Config.Credentials.Get()
assert.NoError(t, err)
assert.True(t, credProvider.retreiveCalled)
}

View File

@@ -1,31 +0,0 @@
package aws
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHandlerList(t *testing.T) {
s := ""
r := &Request{}
l := HandlerList{}
l.PushBack(func(r *Request) {
s += "a"
r.Data = s
})
l.Run(r)
assert.Equal(t, "a", s)
assert.Equal(t, "a", r.Data)
}
func TestMultipleHandlers(t *testing.T) {
r := &Request{}
l := HandlerList{}
l.PushBack(func(r *Request) { r.Data = nil })
l.PushFront(func(r *Request) { r.Data = Boolean(true) })
l.Run(r)
if r.Data != nil {
t.Error("Expected handler to execute")
}
}

View File

@@ -0,0 +1,98 @@
package aws
import (
"log"
"os"
)
// A LogLevelType defines the level logging should be performed at. Used to instruct
// the SDK which statements should be logged.
type LogLevelType uint
// LogLevel returns the pointer to a LogLevel. Should be used to workaround
// not being able to take the address of a non-composite literal.
func LogLevel(l LogLevelType) *LogLevelType {
return &l
}
// Value returns the LogLevel value or the default value LogOff if the LogLevel
// is nil. Safe to use on nil value LogLevelTypes.
func (l *LogLevelType) Value() LogLevelType {
if l != nil {
return *l
}
return LogOff
}
// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be
// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If
// LogLevel is nill, will default to LogOff comparison.
func (l *LogLevelType) Matches(v LogLevelType) bool {
c := l.Value()
return c&v == v
}
// AtLeast returns true if this LogLevel is at least high enough to satisfies v.
// Is safe to use on nil value LogLevelTypes. If LogLevel is nill, will default
// to LogOff comparison.
func (l *LogLevelType) AtLeast(v LogLevelType) bool {
c := l.Value()
return c >= v
}
const (
// LogOff states that no logging should be performed by the SDK. This is the
// default state of the SDK, and should be use to disable all logging.
LogOff LogLevelType = iota * 0x1000
// LogDebug state that debug output should be logged by the SDK. This should
// be used to inspect request made and responses received.
LogDebug
)
// Debug Logging Sub Levels
const (
// LogDebugWithSigning states that the SDK should log request signing and
// presigning events. This should be used to log the signing details of
// requests for debugging. Will also enable LogDebug.
LogDebugWithSigning LogLevelType = LogDebug | (1 << iota)
// LogDebugWithHTTPBody states the SDK should log HTTP request and response
// HTTP bodys in addition to the headers and path. This should be used to
// see the body content of requests and responses made while using the SDK
// Will also enable LogDebug.
LogDebugWithHTTPBody
// LogDebugWithRequestRetries states the SDK should log when service requests will
// be retried. This should be used to log when you want to log when service
// requests are being retried. Will also enable LogDebug.
LogDebugWithRequestRetries
// LogDebugWithRequestErrors states the SDK should log when service requests fail
// to build, send, validate, or unmarshal.
LogDebugWithRequestErrors
)
// A Logger is a minimalistic interface for the SDK to log messages to. Should
// be used to provide custom logging writers for the SDK to use.
type Logger interface {
Log(...interface{})
}
// NewDefaultLogger returns a Logger which will write log messages to stdout, and
// use same formatting runes as the stdlib log.Logger
func NewDefaultLogger() Logger {
return &defaultLogger{
logger: log.New(os.Stdout, "", log.LstdFlags),
}
}
// A defaultLogger provides a minimalistic logger satisfying the Logger interface.
type defaultLogger struct {
logger *log.Logger
}
// Log logs the parameters to the stdlib logger. See log.Println.
func (l defaultLogger) Log(args ...interface{}) {
l.logger.Println(args...)
}

View File

@@ -1,89 +0,0 @@
package aws
import (
"fmt"
"reflect"
"strings"
"github.com/aws/aws-sdk-go/internal/apierr"
)
// ValidateParameters is a request handler to validate the input parameters.
// Validating parameters only has meaning if done prior to the request being sent.
func ValidateParameters(r *Request) {
if r.ParamsFilled() {
v := validator{errors: []string{}}
v.validateAny(reflect.ValueOf(r.Params), "")
if count := len(v.errors); count > 0 {
format := "%d validation errors:\n- %s"
msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- "))
r.Error = apierr.New("InvalidParameter", msg, nil)
}
}
}
// A validator validates values. Collects validations errors which occurs.
type validator struct {
errors []string
}
// validateAny will validate any struct, slice or map type. All validations
// are also performed recursively for nested types.
func (v *validator) validateAny(value reflect.Value, path string) {
value = reflect.Indirect(value)
if !value.IsValid() {
return
}
switch value.Kind() {
case reflect.Struct:
v.validateStruct(value, path)
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i))
}
case reflect.Map:
for _, n := range value.MapKeys() {
v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String()))
}
}
}
// validateStruct will validate the struct value's fields. If the structure has
// nested types those types will be validated also.
func (v *validator) validateStruct(value reflect.Value, path string) {
prefix := "."
if path == "" {
prefix = ""
}
for i := 0; i < value.Type().NumField(); i++ {
f := value.Type().Field(i)
if strings.ToLower(f.Name[0:1]) == f.Name[0:1] {
continue
}
fvalue := value.FieldByName(f.Name)
notset := false
if f.Tag.Get("required") != "" {
switch fvalue.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Map:
if fvalue.IsNil() {
notset = true
}
default:
if !fvalue.IsValid() {
notset = true
}
}
}
if notset {
msg := "missing required parameter: " + path + prefix + f.Name
v.errors = append(v.errors, msg)
} else {
v.validateAny(fvalue, path+prefix+f.Name)
}
}
}

View File

@@ -1,84 +0,0 @@
package aws_test
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/stretchr/testify/assert"
)
var service = func() *aws.Service {
s := &aws.Service{
Config: &aws.Config{},
ServiceName: "mock-service",
APIVersion: "2015-01-01",
}
return s
}()
type StructShape struct {
RequiredList []*ConditionalStructShape `required:"true"`
RequiredMap map[string]*ConditionalStructShape `required:"true"`
RequiredBool *bool `required:"true"`
OptionalStruct *ConditionalStructShape
hiddenParameter *string
metadataStructureShape
}
type metadataStructureShape struct {
SDKShapeTraits bool
}
type ConditionalStructShape struct {
Name *string `required:"true"`
SDKShapeTraits bool
}
func TestNoErrors(t *testing.T) {
input := &StructShape{
RequiredList: []*ConditionalStructShape{},
RequiredMap: map[string]*ConditionalStructShape{
"key1": &ConditionalStructShape{Name: aws.String("Name")},
"key2": &ConditionalStructShape{Name: aws.String("Name")},
},
RequiredBool: aws.Boolean(true),
OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
}
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
aws.ValidateParameters(req)
assert.NoError(t, req.Error)
}
func TestMissingRequiredParameters(t *testing.T) {
input := &StructShape{}
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
aws.ValidateParameters(req)
assert.Error(t, req.Error)
assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message())
}
func TestNestedMissingRequiredParameters(t *testing.T) {
input := &StructShape{
RequiredList: []*ConditionalStructShape{&ConditionalStructShape{}},
RequiredMap: map[string]*ConditionalStructShape{
"key1": &ConditionalStructShape{Name: aws.String("Name")},
"key2": &ConditionalStructShape{},
},
RequiredBool: aws.Boolean(true),
OptionalStruct: &ConditionalStructShape{},
}
req := aws.NewRequest(service, &aws.Operation{}, input, nil)
aws.ValidateParameters(req)
assert.Error(t, req.Error)
assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message())
}

View File

@@ -1,4 +1,4 @@
package aws package request
// A Handlers provides a collection of request handlers for various // A Handlers provides a collection of request handlers for various
// stages of handling requests. // stages of handling requests.
@@ -15,8 +15,8 @@ type Handlers struct {
AfterRetry HandlerList AfterRetry HandlerList
} }
// copy returns of this handler's lists. // Copy returns of this handler's lists.
func (h *Handlers) copy() Handlers { func (h *Handlers) Copy() Handlers {
return Handlers{ return Handlers{
Validate: h.Validate.copy(), Validate: h.Validate.copy(),
Build: h.Build.copy(), Build: h.Build.copy(),
@@ -47,19 +47,25 @@ func (h *Handlers) Clear() {
// A HandlerList manages zero or more handlers in a list. // A HandlerList manages zero or more handlers in a list.
type HandlerList struct { type HandlerList struct {
list []func(*Request) list []NamedHandler
}
// A NamedHandler is a struct that contains a name and function callback.
type NamedHandler struct {
Name string
Fn func(*Request)
} }
// copy creates a copy of the handler list. // copy creates a copy of the handler list.
func (l *HandlerList) copy() HandlerList { func (l *HandlerList) copy() HandlerList {
var n HandlerList var n HandlerList
n.list = append([]func(*Request){}, l.list...) n.list = append([]NamedHandler{}, l.list...)
return n return n
} }
// Clear clears the handler list. // Clear clears the handler list.
func (l *HandlerList) Clear() { func (l *HandlerList) Clear() {
l.list = []func(*Request){} l.list = []NamedHandler{}
} }
// Len returns the number of handlers in the list. // Len returns the number of handlers in the list.
@@ -67,19 +73,40 @@ func (l *HandlerList) Len() int {
return len(l.list) return len(l.list)
} }
// PushBack pushes handlers f to the back of the handler list. // PushBack pushes handler f to the back of the handler list.
func (l *HandlerList) PushBack(f ...func(*Request)) { func (l *HandlerList) PushBack(f func(*Request)) {
l.list = append(l.list, f...) l.list = append(l.list, NamedHandler{"__anonymous", f})
} }
// PushFront pushes handlers f to the front of the handler list. // PushFront pushes handler f to the front of the handler list.
func (l *HandlerList) PushFront(f ...func(*Request)) { func (l *HandlerList) PushFront(f func(*Request)) {
l.list = append(f, l.list...) l.list = append([]NamedHandler{{"__anonymous", f}}, l.list...)
}
// PushBackNamed pushes named handler f to the back of the handler list.
func (l *HandlerList) PushBackNamed(n NamedHandler) {
l.list = append(l.list, n)
}
// PushFrontNamed pushes named handler f to the front of the handler list.
func (l *HandlerList) PushFrontNamed(n NamedHandler) {
l.list = append([]NamedHandler{n}, l.list...)
}
// Remove removes a NamedHandler n
func (l *HandlerList) Remove(n NamedHandler) {
newlist := []NamedHandler{}
for _, m := range l.list {
if m.Name != n.Name {
newlist = append(newlist, m)
}
}
l.list = newlist
} }
// Run executes all handlers in the list with a given request object. // Run executes all handlers in the list with a given request object.
func (l *HandlerList) Run(r *Request) { func (l *HandlerList) Run(r *Request) {
for _, f := range l.list { for _, f := range l.list {
f(r) f.Fn(r)
} }
} }

View File

@@ -0,0 +1,47 @@
package request_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
func TestHandlerList(t *testing.T) {
s := ""
r := &request.Request{}
l := request.HandlerList{}
l.PushBack(func(r *request.Request) {
s += "a"
r.Data = s
})
l.Run(r)
assert.Equal(t, "a", s)
assert.Equal(t, "a", r.Data)
}
func TestMultipleHandlers(t *testing.T) {
r := &request.Request{}
l := request.HandlerList{}
l.PushBack(func(r *request.Request) { r.Data = nil })
l.PushFront(func(r *request.Request) { r.Data = aws.Bool(true) })
l.Run(r)
if r.Data != nil {
t.Error("Expected handler to execute")
}
}
func TestNamedHandlers(t *testing.T) {
l := request.HandlerList{}
named := request.NamedHandler{"Name", func(r *request.Request) {}}
named2 := request.NamedHandler{"NotName", func(r *request.Request) {}}
l.PushBackNamed(named)
l.PushBackNamed(named)
l.PushBackNamed(named2)
l.PushBack(func(r *request.Request) {})
assert.Equal(t, 4, l.Len())
l.Remove(named)
assert.Equal(t, 2, l.Len())
}

View File

@@ -1,7 +1,8 @@
package aws package request
import ( import (
"bytes" "bytes"
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@@ -10,12 +11,15 @@ import (
"strings" "strings"
"time" "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
) )
// A Request is the service request to be made. // A Request is the service request to be made.
type Request struct { type Request struct {
*Service Retryer
Service serviceinfo.ServiceInfo
Handlers Handlers Handlers Handlers
Time time.Time Time time.Time
ExpireTime time.Duration ExpireTime time.Duration
@@ -23,17 +27,16 @@ type Request struct {
HTTPRequest *http.Request HTTPRequest *http.Request
HTTPResponse *http.Response HTTPResponse *http.Response
Body io.ReadSeeker Body io.ReadSeeker
bodyStart int64 // offset from beginning of Body that the request body starts BodyStart int64 // offset from beginning of Body that the request body starts
Params interface{} Params interface{}
Error error Error error
Data interface{} Data interface{}
RequestID string RequestID string
RetryCount uint RetryCount uint
Retryable SettableBool Retryable *bool
RetryDelay time.Duration RetryDelay time.Duration
built bool built bool
signed bool
} }
// An Operation is the service API operation to be made. // An Operation is the service API operation to be made.
@@ -52,13 +55,13 @@ type Paginator struct {
TruncationToken string TruncationToken string
} }
// NewRequest returns a new Request pointer for the service API // New returns a new Request pointer for the service API
// operation and parameters. // operation and parameters.
// //
// Params is any value of input parameters to be the request payload. // Params is any value of input parameters to be the request payload.
// Data is pointer value to an object which the request's response // Data is pointer value to an object which the request's response
// payload will be deserialized to. // payload will be deserialized to.
func NewRequest(service *Service, operation *Operation, params interface{}, data interface{}) *Request { func New(service serviceinfo.ServiceInfo, handlers Handlers, retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request {
method := operation.HTTPMethod method := operation.HTTPMethod
if method == "" { if method == "" {
method = "POST" method = "POST"
@@ -72,8 +75,9 @@ func NewRequest(service *Service, operation *Operation, params interface{}, data
httpReq.URL, _ = url.Parse(service.Endpoint + p) httpReq.URL, _ = url.Parse(service.Endpoint + p)
r := &Request{ r := &Request{
Retryer: retryer,
Service: service, Service: service,
Handlers: service.Handlers.copy(), Handlers: handlers.Copy(),
Time: time.Now(), Time: time.Now(),
ExpireTime: 0, ExpireTime: 0,
Operation: operation, Operation: operation,
@@ -90,7 +94,7 @@ func NewRequest(service *Service, operation *Operation, params interface{}, data
// WillRetry returns if the request's can be retried. // WillRetry returns if the request's can be retried.
func (r *Request) WillRetry() bool { func (r *Request) WillRetry() bool {
return r.Error != nil && r.Retryable.Get() && r.RetryCount < r.Service.MaxRetries() return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries()
} }
// ParamsFilled returns if the request's parameters have been populated // ParamsFilled returns if the request's parameters have been populated
@@ -135,6 +139,20 @@ func (r *Request) Presign(expireTime time.Duration) (string, error) {
return r.HTTPRequest.URL.String(), nil return r.HTTPRequest.URL.String(), nil
} }
func debugLogReqError(r *Request, stage string, retrying bool, err error) {
if !r.Service.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) {
return
}
retryStr := "not retrying"
if retrying {
retryStr = "will retry"
}
r.Service.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v",
stage, r.Service.ServiceName, r.Operation.Name, retryStr, err))
}
// Build will build the request's object so it can be signed and sent // Build will build the request's object so it can be signed and sent
// to the service. Build will also validate all the request's parameters. // to the service. Build will also validate all the request's parameters.
// Anny additional build Handlers set on this request will be run // Anny additional build Handlers set on this request will be run
@@ -150,6 +168,7 @@ func (r *Request) Build() error {
r.Error = nil r.Error = nil
r.Handlers.Validate.Run(r) r.Handlers.Validate.Run(r)
if r.Error != nil { if r.Error != nil {
debugLogReqError(r, "Validate Request", false, r.Error)
return r.Error return r.Error
} }
r.Handlers.Build.Run(r) r.Handlers.Build.Run(r)
@@ -164,17 +183,13 @@ func (r *Request) Build() error {
// Send will build the request prior to signing. All Sign Handlers will // Send will build the request prior to signing. All Sign Handlers will
// be executed in the order they were set. // be executed in the order they were set.
func (r *Request) Sign() error { func (r *Request) Sign() error {
if r.signed {
return r.Error
}
r.Build() r.Build()
if r.Error != nil { if r.Error != nil {
debugLogReqError(r, "Build Request", false, r.Error)
return r.Error return r.Error
} }
r.Handlers.Sign.Run(r) r.Handlers.Sign.Run(r)
r.signed = r.Error != nil
return r.Error return r.Error
} }
@@ -189,42 +204,57 @@ func (r *Request) Send() error {
return r.Error return r.Error
} }
if r.Retryable.Get() { if aws.BoolValue(r.Retryable) {
if r.Service.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) {
r.Service.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d",
r.Service.ServiceName, r.Operation.Name, r.RetryCount))
}
// Re-seek the body back to the original point in for a retry so that // Re-seek the body back to the original point in for a retry so that
// send will send the body's contents again in the upcoming request. // send will send the body's contents again in the upcoming request.
r.Body.Seek(r.bodyStart, 0) r.Body.Seek(r.BodyStart, 0)
r.HTTPRequest.Body = ioutil.NopCloser(r.Body)
} }
r.Retryable.Reset() r.Retryable = nil
r.Handlers.Send.Run(r) r.Handlers.Send.Run(r)
if r.Error != nil { if r.Error != nil {
err := r.Error
r.Handlers.Retry.Run(r) r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r) r.Handlers.AfterRetry.Run(r)
if r.Error != nil { if r.Error != nil {
debugLogReqError(r, "Send Request", false, r.Error)
return r.Error return r.Error
} }
debugLogReqError(r, "Send Request", true, err)
continue continue
} }
r.Handlers.UnmarshalMeta.Run(r) r.Handlers.UnmarshalMeta.Run(r)
r.Handlers.ValidateResponse.Run(r) r.Handlers.ValidateResponse.Run(r)
if r.Error != nil { if r.Error != nil {
err := r.Error
r.Handlers.UnmarshalError.Run(r) r.Handlers.UnmarshalError.Run(r)
r.Handlers.Retry.Run(r) r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r) r.Handlers.AfterRetry.Run(r)
if r.Error != nil { if r.Error != nil {
debugLogReqError(r, "Validate Response", false, r.Error)
return r.Error return r.Error
} }
debugLogReqError(r, "Validate Response", true, err)
continue continue
} }
r.Handlers.Unmarshal.Run(r) r.Handlers.Unmarshal.Run(r)
if r.Error != nil { if r.Error != nil {
err := r.Error
r.Handlers.Retry.Run(r) r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r) r.Handlers.AfterRetry.Run(r)
if r.Error != nil { if r.Error != nil {
debugLogReqError(r, "Unmarshal Response", false, r.Error)
return r.Error return r.Error
} }
debugLogReqError(r, "Unmarshal Response", true, err)
continue continue
} }
@@ -285,7 +315,7 @@ func (r *Request) NextPage() *Request {
} }
data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface()
nr := NewRequest(r.Service, r.Operation, awsutil.CopyOf(r.Params), data) nr := New(r.Service, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data)
for i, intok := range nr.Operation.InputTokens { for i, intok := range nr.Operation.InputTokens {
awsutil.SetValueAtAnyPath(nr.Params, intok, tokens[i]) awsutil.SetValueAtAnyPath(nr.Params, intok, tokens[i])
} }

View File

@@ -1,13 +1,15 @@
package aws_test package request_test
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/test/unit" "github.com/aws/aws-sdk-go/internal/test/unit"
"github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3"
"github.com/stretchr/testify/assert"
) )
var _ = unit.Imported var _ = unit.Imported
@@ -19,16 +21,16 @@ func TestPagination(t *testing.T) {
reqNum := 0 reqNum := 0
resps := []*dynamodb.ListTablesOutput{ resps := []*dynamodb.ListTablesOutput{
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, {TableNames: []*string{aws.String("Table5")}},
} }
db.Handlers.Send.Clear() // mock sending db.Handlers.Send.Clear() // mock sending
db.Handlers.Unmarshal.Clear() db.Handlers.Unmarshal.Clear()
db.Handlers.UnmarshalMeta.Clear() db.Handlers.UnmarshalMeta.Clear()
db.Handlers.ValidateResponse.Clear() db.Handlers.ValidateResponse.Clear()
db.Handlers.Build.PushBack(func(r *aws.Request) { db.Handlers.Build.PushBack(func(r *request.Request) {
in := r.Params.(*dynamodb.ListTablesInput) in := r.Params.(*dynamodb.ListTablesInput)
if in == nil { if in == nil {
tokens = append(tokens, "") tokens = append(tokens, "")
@@ -36,12 +38,12 @@ func TestPagination(t *testing.T) {
tokens = append(tokens, *in.ExclusiveStartTableName) tokens = append(tokens, *in.ExclusiveStartTableName)
} }
}) })
db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = resps[reqNum] r.Data = resps[reqNum]
reqNum++ reqNum++
}) })
params := &dynamodb.ListTablesInput{Limit: aws.Long(2)} params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool {
numPages++ numPages++
for _, t := range p.TableNames { for _, t := range p.TableNames {
@@ -71,16 +73,16 @@ func TestPaginationEachPage(t *testing.T) {
reqNum := 0 reqNum := 0
resps := []*dynamodb.ListTablesOutput{ resps := []*dynamodb.ListTablesOutput{
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, {TableNames: []*string{aws.String("Table5")}},
} }
db.Handlers.Send.Clear() // mock sending db.Handlers.Send.Clear() // mock sending
db.Handlers.Unmarshal.Clear() db.Handlers.Unmarshal.Clear()
db.Handlers.UnmarshalMeta.Clear() db.Handlers.UnmarshalMeta.Clear()
db.Handlers.ValidateResponse.Clear() db.Handlers.ValidateResponse.Clear()
db.Handlers.Build.PushBack(func(r *aws.Request) { db.Handlers.Build.PushBack(func(r *request.Request) {
in := r.Params.(*dynamodb.ListTablesInput) in := r.Params.(*dynamodb.ListTablesInput)
if in == nil { if in == nil {
tokens = append(tokens, "") tokens = append(tokens, "")
@@ -88,12 +90,12 @@ func TestPaginationEachPage(t *testing.T) {
tokens = append(tokens, *in.ExclusiveStartTableName) tokens = append(tokens, *in.ExclusiveStartTableName)
} }
}) })
db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = resps[reqNum] r.Data = resps[reqNum]
reqNum++ reqNum++
}) })
params := &dynamodb.ListTablesInput{Limit: aws.Long(2)} params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
req, _ := db.ListTablesRequest(params) req, _ := db.ListTablesRequest(params)
err := req.EachPage(func(p interface{}, last bool) bool { err := req.EachPage(func(p interface{}, last bool) bool {
numPages++ numPages++
@@ -124,21 +126,21 @@ func TestPaginationEarlyExit(t *testing.T) {
reqNum := 0 reqNum := 0
resps := []*dynamodb.ListTablesOutput{ resps := []*dynamodb.ListTablesOutput{
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, {TableNames: []*string{aws.String("Table5")}},
} }
db.Handlers.Send.Clear() // mock sending db.Handlers.Send.Clear() // mock sending
db.Handlers.Unmarshal.Clear() db.Handlers.Unmarshal.Clear()
db.Handlers.UnmarshalMeta.Clear() db.Handlers.UnmarshalMeta.Clear()
db.Handlers.ValidateResponse.Clear() db.Handlers.ValidateResponse.Clear()
db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = resps[reqNum] r.Data = resps[reqNum]
reqNum++ reqNum++
}) })
params := &dynamodb.ListTablesInput{Limit: aws.Long(2)} params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool {
numPages++ numPages++
if numPages == 2 { if numPages == 2 {
@@ -164,7 +166,7 @@ func TestSkipPagination(t *testing.T) {
client.Handlers.Unmarshal.Clear() client.Handlers.Unmarshal.Clear()
client.Handlers.UnmarshalMeta.Clear() client.Handlers.UnmarshalMeta.Clear()
client.Handlers.ValidateResponse.Clear() client.Handlers.ValidateResponse.Clear()
client.Handlers.Unmarshal.PushBack(func(r *aws.Request) { client.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = &s3.HeadBucketOutput{} r.Data = &s3.HeadBucketOutput{}
}) })
@@ -189,17 +191,17 @@ func TestPaginationTruncation(t *testing.T) {
reqNum := &count reqNum := &count
resps := []*s3.ListObjectsOutput{ resps := []*s3.ListObjectsOutput{
&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key1")}}}, {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}},
&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key2")}}}, {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}},
&s3.ListObjectsOutput{IsTruncated: aws.Boolean(false), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key3")}}}, {IsTruncated: aws.Bool(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}},
&s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key4")}}}, {IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}},
} }
client.Handlers.Send.Clear() // mock sending client.Handlers.Send.Clear() // mock sending
client.Handlers.Unmarshal.Clear() client.Handlers.Unmarshal.Clear()
client.Handlers.UnmarshalMeta.Clear() client.Handlers.UnmarshalMeta.Clear()
client.Handlers.ValidateResponse.Clear() client.Handlers.ValidateResponse.Clear()
client.Handlers.Unmarshal.PushBack(func(r *aws.Request) { client.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = resps[*reqNum] r.Data = resps[*reqNum]
*reqNum++ *reqNum++
}) })
@@ -218,7 +220,7 @@ func TestPaginationTruncation(t *testing.T) {
// Try again without truncation token at all // Try again without truncation token at all
count = 0 count = 0
resps[1].IsTruncated = nil resps[1].IsTruncated = nil
resps[2].IsTruncated = aws.Boolean(true) resps[2].IsTruncated = aws.Bool(true)
results = []string{} results = []string{}
err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool {
results = append(results, *p.Contents[0].Key) results = append(results, *p.Contents[0].Key)
@@ -232,20 +234,20 @@ func TestPaginationTruncation(t *testing.T) {
// Benchmarks // Benchmarks
var benchResps = []*dynamodb.ListTablesOutput{ var benchResps = []*dynamodb.ListTablesOutput{
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")},
&dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE")}}, {TableNames: []*string{aws.String("TABLE")}},
} }
var benchDb = func() *dynamodb.DynamoDB { var benchDb = func() *dynamodb.DynamoDB {
@@ -260,12 +262,12 @@ var benchDb = func() *dynamodb.DynamoDB {
func BenchmarkCodegenIterator(b *testing.B) { func BenchmarkCodegenIterator(b *testing.B) {
reqNum := 0 reqNum := 0
db := benchDb() db := benchDb()
db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = benchResps[reqNum] r.Data = benchResps[reqNum]
reqNum++ reqNum++
}) })
input := &dynamodb.ListTablesInput{Limit: aws.Long(2)} input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error { iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error {
page, _ := db.ListTablesRequest(input) page, _ := db.ListTablesRequest(input)
for ; page != nil; page = page.NextPage() { for ; page != nil; page = page.NextPage() {
@@ -289,12 +291,12 @@ func BenchmarkCodegenIterator(b *testing.B) {
func BenchmarkEachPageIterator(b *testing.B) { func BenchmarkEachPageIterator(b *testing.B) {
reqNum := 0 reqNum := 0
db := benchDb() db := benchDb()
db.Handlers.Unmarshal.PushBack(func(r *aws.Request) { db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
r.Data = benchResps[reqNum] r.Data = benchResps[reqNum]
reqNum++ reqNum++
}) })
input := &dynamodb.ListTablesInput{Limit: aws.Long(2)} input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
reqNum = 0 reqNum = 0
req, _ := db.ListTablesRequest(input) req, _ := db.ListTablesRequest(input)

View File

@@ -1,4 +1,4 @@
package aws package request_test
import ( import (
"bytes" "bytes"
@@ -7,13 +7,14 @@ import (
"io" "io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"reflect"
"testing" "testing"
"time" "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -25,7 +26,7 @@ func body(str string) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader([]byte(str))) return ioutil.NopCloser(bytes.NewReader([]byte(str)))
} }
func unmarshal(req *Request) { func unmarshal(req *request.Request) {
defer req.HTTPResponse.Body.Close() defer req.HTTPResponse.Body.Close()
if req.Data != nil { if req.Data != nil {
json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data)
@@ -33,15 +34,15 @@ func unmarshal(req *Request) {
return return
} }
func unmarshalError(req *Request) { func unmarshalError(req *request.Request) {
bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body)
if err != nil { if err != nil {
req.Error = apierr.New("UnmarshaleError", req.HTTPResponse.Status, err) req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err)
return return
} }
if len(bodyBytes) == 0 { if len(bodyBytes) == 0 {
req.Error = apierr.NewRequestError( req.Error = awserr.NewRequestFailure(
apierr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")),
req.HTTPResponse.StatusCode, req.HTTPResponse.StatusCode,
"", "",
) )
@@ -49,11 +50,11 @@ func unmarshalError(req *Request) {
} }
var jsonErr jsonErrorResponse var jsonErr jsonErrorResponse
if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
req.Error = apierr.New("UnmarshaleError", "JSON unmarshal", err) req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err)
return return
} }
req.Error = apierr.NewRequestError( req.Error = awserr.NewRequestFailure(
apierr.New(jsonErr.Code, jsonErr.Message, nil), awserr.New(jsonErr.Code, jsonErr.Message, nil),
req.HTTPResponse.StatusCode, req.HTTPResponse.StatusCode,
"", "",
) )
@@ -68,22 +69,22 @@ type jsonErrorResponse struct {
func TestRequestRecoverRetry5xx(t *testing.T) { func TestRequestRecoverRetry5xx(t *testing.T) {
reqNum := 0 reqNum := 0
reqs := []http.Response{ reqs := []http.Response{
http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
http.Response{StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)},
} }
s := NewService(&Config{MaxRetries: 10}) s := service.New(aws.NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear() s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.UnmarshalError.PushBack(unmarshalError)
s.Handlers.Send.Clear() // mock sending s.Handlers.Send.Clear() // mock sending
s.Handlers.Send.PushBack(func(r *Request) { s.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &reqs[reqNum] r.HTTPResponse = &reqs[reqNum]
reqNum++ reqNum++
}) })
out := &testData{} out := &testData{}
r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out)
err := r.Send() err := r.Send()
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 2, int(r.RetryCount)) assert.Equal(t, 2, int(r.RetryCount))
@@ -94,22 +95,22 @@ func TestRequestRecoverRetry5xx(t *testing.T) {
func TestRequestRecoverRetry4xxRetryable(t *testing.T) { func TestRequestRecoverRetry4xxRetryable(t *testing.T) {
reqNum := 0 reqNum := 0
reqs := []http.Response{ reqs := []http.Response{
http.Response{StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, {StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)},
http.Response{StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, {StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)},
http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)},
} }
s := NewService(&Config{MaxRetries: 10}) s := service.New(aws.NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear() s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.UnmarshalError.PushBack(unmarshalError)
s.Handlers.Send.Clear() // mock sending s.Handlers.Send.Clear() // mock sending
s.Handlers.Send.PushBack(func(r *Request) { s.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &reqs[reqNum] r.HTTPResponse = &reqs[reqNum]
reqNum++ reqNum++
}) })
out := &testData{} out := &testData{}
r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out)
err := r.Send() err := r.Send()
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 2, int(r.RetryCount)) assert.Equal(t, 2, int(r.RetryCount))
@@ -118,16 +119,16 @@ func TestRequestRecoverRetry4xxRetryable(t *testing.T) {
// test that retries don't occur for 4xx status codes with a response type that can't be retried // test that retries don't occur for 4xx status codes with a response type that can't be retried
func TestRequest4xxUnretryable(t *testing.T) { func TestRequest4xxUnretryable(t *testing.T) {
s := NewService(&Config{MaxRetries: 10}) s := service.New(aws.NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear() s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.UnmarshalError.PushBack(unmarshalError)
s.Handlers.Send.Clear() // mock sending s.Handlers.Send.Clear() // mock sending
s.Handlers.Send.PushBack(func(r *Request) { s.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)}
}) })
out := &testData{} out := &testData{}
r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out)
err := r.Send() err := r.Send()
assert.NotNil(t, err) assert.NotNil(t, err)
if e, ok := err.(awserr.RequestFailure); ok { if e, ok := err.(awserr.RequestFailure); ok {
@@ -142,28 +143,28 @@ func TestRequest4xxUnretryable(t *testing.T) {
func TestRequestExhaustRetries(t *testing.T) { func TestRequestExhaustRetries(t *testing.T) {
delays := []time.Duration{} delays := []time.Duration{}
sleepDelay = func(delay time.Duration) { sleepDelay := func(delay time.Duration) {
delays = append(delays, delay) delays = append(delays, delay)
} }
reqNum := 0 reqNum := 0
reqs := []http.Response{ reqs := []http.Response{
http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
} }
s := NewService(&Config{MaxRetries: -1}) s := service.New(aws.NewConfig().WithMaxRetries(aws.DefaultRetries).WithSleepDelay(sleepDelay))
s.Handlers.Validate.Clear() s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.UnmarshalError.PushBack(unmarshalError)
s.Handlers.Send.Clear() // mock sending s.Handlers.Send.Clear() // mock sending
s.Handlers.Send.PushBack(func(r *Request) { s.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &reqs[reqNum] r.HTTPResponse = &reqs[reqNum]
reqNum++ reqNum++
}) })
r := NewRequest(s, &Operation{Name: "Operation"}, nil, nil) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
err := r.Send() err := r.Send()
assert.NotNil(t, err) assert.NotNil(t, err)
if e, ok := err.(awserr.RequestFailure); ok { if e, ok := err.(awserr.RequestFailure); ok {
@@ -174,18 +175,25 @@ func TestRequestExhaustRetries(t *testing.T) {
assert.Equal(t, "UnknownError", err.(awserr.Error).Code()) assert.Equal(t, "UnknownError", err.(awserr.Error).Code())
assert.Equal(t, "An error occurred.", err.(awserr.Error).Message()) assert.Equal(t, "An error occurred.", err.(awserr.Error).Message())
assert.Equal(t, 3, int(r.RetryCount)) assert.Equal(t, 3, int(r.RetryCount))
assert.True(t, reflect.DeepEqual([]time.Duration{30 * time.Millisecond, 60 * time.Millisecond, 120 * time.Millisecond}, delays))
expectDelays := []struct{ min, max time.Duration }{{30, 59}, {60, 118}, {120, 236}}
for i, v := range delays {
min := expectDelays[i].min * time.Millisecond
max := expectDelays[i].max * time.Millisecond
assert.True(t, min <= v && v <= max,
"Expect delay to be within range, i:%d, v:%s, min:%s, max:%s", i, v, min, max)
}
} }
// test that the request is retried after the credentials are expired. // test that the request is retried after the credentials are expired.
func TestRequestRecoverExpiredCreds(t *testing.T) { func TestRequestRecoverExpiredCreds(t *testing.T) {
reqNum := 0 reqNum := 0
reqs := []http.Response{ reqs := []http.Response{
http.Response{StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, {StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)},
http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, {StatusCode: 200, Body: body(`{"data":"valid"}`)},
} }
s := NewService(&Config{MaxRetries: 10, Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) s := service.New(&aws.Config{MaxRetries: aws.Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")})
s.Handlers.Validate.Clear() s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal) s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError) s.Handlers.UnmarshalError.PushBack(unmarshalError)
@@ -193,21 +201,21 @@ func TestRequestRecoverExpiredCreds(t *testing.T) {
credExpiredBeforeRetry := false credExpiredBeforeRetry := false
credExpiredAfterRetry := false credExpiredAfterRetry := false
s.Handlers.AfterRetry.PushBack(func(r *Request) { s.Handlers.AfterRetry.PushBack(func(r *request.Request) {
credExpiredAfterRetry = r.Config.Credentials.IsExpired() credExpiredAfterRetry = r.Service.Config.Credentials.IsExpired()
}) })
s.Handlers.Sign.Clear() s.Handlers.Sign.Clear()
s.Handlers.Sign.PushBack(func(r *Request) { s.Handlers.Sign.PushBack(func(r *request.Request) {
r.Config.Credentials.Get() r.Service.Config.Credentials.Get()
}) })
s.Handlers.Send.Clear() // mock sending s.Handlers.Send.Clear() // mock sending
s.Handlers.Send.PushBack(func(r *Request) { s.Handlers.Send.PushBack(func(r *request.Request) {
r.HTTPResponse = &reqs[reqNum] r.HTTPResponse = &reqs[reqNum]
reqNum++ reqNum++
}) })
out := &testData{} out := &testData{}
r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out)
err := r.Send() err := r.Send()
assert.Nil(t, err) assert.Nil(t, err)

View File

@@ -0,0 +1,71 @@
package request
import (
"time"
"github.com/aws/aws-sdk-go/aws/awserr"
)
// Retryer is an interface to control retry logic for a given service.
// The default implementation used by most services is the service.DefaultRetryer
// structure, which contains basic retry logic using exponential backoff.
type Retryer interface {
RetryRules(*Request) time.Duration
ShouldRetry(*Request) bool
MaxRetries() uint
}
// retryableCodes is a collection of service response codes which are retry-able
// without any further action.
var retryableCodes = map[string]struct{}{
"RequestError": {},
"ProvisionedThroughputExceededException": {},
"Throttling": {},
"ThrottlingException": {},
"RequestLimitExceeded": {},
"RequestThrottled": {},
}
// credsExpiredCodes is a collection of error codes which signify the credentials
// need to be refreshed. Expired tokens require refreshing of credentials, and
// resigning before the request can be retried.
var credsExpiredCodes = map[string]struct{}{
"ExpiredToken": {},
"ExpiredTokenException": {},
"RequestExpired": {}, // EC2 Only
}
func isCodeRetryable(code string) bool {
if _, ok := retryableCodes[code]; ok {
return true
}
return isCodeExpiredCreds(code)
}
func isCodeExpiredCreds(code string) bool {
_, ok := credsExpiredCodes[code]
return ok
}
// IsErrorRetryable returns whether the error is retryable, based on its Code.
// Returns false if the request has no Error set.
func (r *Request) IsErrorRetryable() bool {
if r.Error != nil {
if err, ok := r.Error.(awserr.Error); ok {
return isCodeRetryable(err.Code())
}
}
return false
}
// IsErrorExpired returns whether the error code is a credential expiry error.
// Returns false if the request has no Error set.
func (r *Request) IsErrorExpired() bool {
if r.Error != nil {
if err, ok := r.Error.(awserr.Error); ok {
return isCodeExpiredCreds(err.Code())
}
}
return false
}

View File

@@ -1,177 +0,0 @@
package aws
import (
"fmt"
"math"
"net/http"
"net/http/httputil"
"regexp"
"time"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/endpoints"
)
// A Service implements the base service request and response handling
// used by all services.
type Service struct {
Config *Config
Handlers Handlers
ManualSend bool
ServiceName string
APIVersion string
Endpoint string
SigningName string
SigningRegion string
JSONVersion string
TargetPrefix string
RetryRules func(*Request) time.Duration
ShouldRetry func(*Request) bool
DefaultMaxRetries uint
}
var schemeRE = regexp.MustCompile("^([^:]+)://")
// NewService will return a pointer to a new Server object initialized.
func NewService(config *Config) *Service {
svc := &Service{Config: config}
svc.Initialize()
return svc
}
// Initialize initializes the service.
func (s *Service) Initialize() {
if s.Config == nil {
s.Config = &Config{}
}
if s.Config.HTTPClient == nil {
s.Config.HTTPClient = http.DefaultClient
}
if s.RetryRules == nil {
s.RetryRules = retryRules
}
if s.ShouldRetry == nil {
s.ShouldRetry = shouldRetry
}
s.DefaultMaxRetries = 3
s.Handlers.Validate.PushBack(ValidateEndpointHandler)
s.Handlers.Build.PushBack(UserAgentHandler)
s.Handlers.Sign.PushBack(BuildContentLength)
s.Handlers.Send.PushBack(SendHandler)
s.Handlers.AfterRetry.PushBack(AfterRetryHandler)
s.Handlers.ValidateResponse.PushBack(ValidateResponseHandler)
s.AddDebugHandlers()
s.buildEndpoint()
if !s.Config.DisableParamValidation {
s.Handlers.Validate.PushBack(ValidateParameters)
}
}
// buildEndpoint builds the endpoint values the service will use to make requests with.
func (s *Service) buildEndpoint() {
if s.Config.Endpoint != "" {
s.Endpoint = s.Config.Endpoint
} else {
s.Endpoint, s.SigningRegion =
endpoints.EndpointForRegion(s.ServiceName, s.Config.Region)
}
if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) {
scheme := "https"
if s.Config.DisableSSL {
scheme = "http"
}
s.Endpoint = scheme + "://" + s.Endpoint
}
}
// AddDebugHandlers injects debug logging handlers into the service to log request
// debug information.
func (s *Service) AddDebugHandlers() {
out := s.Config.Logger
if s.Config.LogLevel == 0 {
return
}
s.Handlers.Send.PushFront(func(r *Request) {
logBody := r.Config.LogHTTPBody
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody)
fmt.Fprintf(out, "---[ REQUEST POST-SIGN ]-----------------------------\n")
fmt.Fprintf(out, "%s\n", string(dumpedBody))
fmt.Fprintf(out, "-----------------------------------------------------\n")
})
s.Handlers.Send.PushBack(func(r *Request) {
fmt.Fprintf(out, "---[ RESPONSE ]--------------------------------------\n")
if r.HTTPResponse != nil {
logBody := r.Config.LogHTTPBody
dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, logBody)
fmt.Fprintf(out, "%s\n", string(dumpedBody))
} else if r.Error != nil {
fmt.Fprintf(out, "%s\n", r.Error)
}
fmt.Fprintf(out, "-----------------------------------------------------\n")
})
}
// MaxRetries returns the number of maximum returns the service will use to make
// an individual API request.
func (s *Service) MaxRetries() uint {
if s.Config.MaxRetries < 0 {
return s.DefaultMaxRetries
}
return uint(s.Config.MaxRetries)
}
// retryRules returns the delay duration before retrying this request again
func retryRules(r *Request) time.Duration {
delay := time.Duration(math.Pow(2, float64(r.RetryCount))) * 30
return delay * time.Millisecond
}
// retryableCodes is a collection of service response codes which are retry-able
// without any further action.
var retryableCodes = map[string]struct{}{
"RequestError": struct{}{},
"ProvisionedThroughputExceededException": struct{}{},
"Throttling": struct{}{},
}
// credsExpiredCodes is a collection of error codes which signify the credentials
// need to be refreshed. Expired tokens require refreshing of credentials, and
// resigning before the request can be retried.
var credsExpiredCodes = map[string]struct{}{
"ExpiredToken": struct{}{},
"ExpiredTokenException": struct{}{},
"RequestExpired": struct{}{}, // EC2 Only
}
func isCodeRetryable(code string) bool {
if _, ok := retryableCodes[code]; ok {
return true
}
return isCodeExpiredCreds(code)
}
func isCodeExpiredCreds(code string) bool {
_, ok := credsExpiredCodes[code]
return ok
}
// shouldRetry returns if the request should be retried.
func shouldRetry(r *Request) bool {
if r.HTTPResponse.StatusCode >= 500 {
return true
}
if r.Error != nil {
if err, ok := r.Error.(awserr.Error); ok {
return isCodeRetryable(err.Code())
}
}
return false
}

View File

@@ -0,0 +1,51 @@
package service
import (
"math"
"math/rand"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
// DefaultRetryer implements basic retry logic using exponential backoff for
// most services. If you want to implement custom retry logic, implement the
// request.Retryer interface or create a structure type that composes this
// struct and override the specific methods. For example, to override only
// the MaxRetries method:
//
// type retryer struct {
// service.DefaultRetryer
// }
//
// // This implementation always has 100 max retries
// func (d retryer) MaxRetries() uint { return 100 }
type DefaultRetryer struct {
*Service
}
// MaxRetries returns the number of maximum returns the service will use to make
// an individual API request.
func (d DefaultRetryer) MaxRetries() uint {
if aws.IntValue(d.Service.Config.MaxRetries) < 0 {
return d.DefaultMaxRetries
}
return uint(aws.IntValue(d.Service.Config.MaxRetries))
}
var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))
// RetryRules returns the delay duration before retrying this request again
func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {
delay := int(math.Pow(2, float64(r.RetryCount))) * (seededRand.Intn(30) + 30)
return time.Duration(delay) * time.Millisecond
}
// ShouldRetry returns if the request should be retried.
func (d DefaultRetryer) ShouldRetry(r *request.Request) bool {
if r.HTTPResponse.StatusCode >= 500 {
return true
}
return r.IsErrorRetryable()
}

View File

@@ -0,0 +1,133 @@
package service
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"regexp"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/endpoints"
)
// A Service implements the base service request and response handling
// used by all services.
type Service struct {
serviceinfo.ServiceInfo
request.Retryer
DefaultMaxRetries uint
Handlers request.Handlers
}
var schemeRE = regexp.MustCompile("^([^:]+)://")
// New will return a pointer to a new Server object initialized.
func New(config *aws.Config) *Service {
svc := &Service{ServiceInfo: serviceinfo.ServiceInfo{Config: config}}
svc.Initialize()
return svc
}
// Initialize initializes the service.
func (s *Service) Initialize() {
if s.Config == nil {
s.Config = &aws.Config{}
}
if s.Config.HTTPClient == nil {
s.Config.HTTPClient = http.DefaultClient
}
if s.Config.SleepDelay == nil {
s.Config.SleepDelay = time.Sleep
}
s.Retryer = DefaultRetryer{s}
s.DefaultMaxRetries = 3
s.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler)
s.Handlers.Build.PushBackNamed(corehandlers.UserAgentHandler)
s.Handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler)
s.Handlers.Send.PushBackNamed(corehandlers.SendHandler)
s.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)
s.Handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler)
if !aws.BoolValue(s.Config.DisableParamValidation) {
s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler)
}
s.AddDebugHandlers()
s.buildEndpoint()
}
// NewRequest returns a new Request pointer for the service API
// operation and parameters.
func (s *Service) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request {
return request.New(s.ServiceInfo, s.Handlers, s.Retryer, operation, params, data)
}
// buildEndpoint builds the endpoint values the service will use to make requests with.
func (s *Service) buildEndpoint() {
if aws.StringValue(s.Config.Endpoint) != "" {
s.Endpoint = *s.Config.Endpoint
} else if s.Endpoint == "" {
s.Endpoint, s.SigningRegion =
endpoints.EndpointForRegion(s.ServiceName, aws.StringValue(s.Config.Region))
}
if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) {
scheme := "https"
if aws.BoolValue(s.Config.DisableSSL) {
scheme = "http"
}
s.Endpoint = scheme + "://" + s.Endpoint
}
}
// AddDebugHandlers injects debug logging handlers into the service to log request
// debug information.
func (s *Service) AddDebugHandlers() {
if !s.Config.LogLevel.AtLeast(aws.LogDebug) {
return
}
s.Handlers.Send.PushFront(logRequest)
s.Handlers.Send.PushBack(logResponse)
}
const logReqMsg = `DEBUG: Request %s/%s Details:
---[ REQUEST POST-SIGN ]-----------------------------
%s
-----------------------------------------------------`
func logRequest(r *request.Request) {
logBody := r.Service.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody)
if logBody {
// Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's
// Body as a NoOpCloser and will not be reset after read by the HTTP
// client reader.
r.Body.Seek(r.BodyStart, 0)
r.HTTPRequest.Body = ioutil.NopCloser(r.Body)
}
r.Service.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.Service.ServiceName, r.Operation.Name, string(dumpedBody)))
}
const logRespMsg = `DEBUG: Response %s/%s Details:
---[ RESPONSE ]--------------------------------------
%s
-----------------------------------------------------`
func logResponse(r *request.Request) {
var msg = "no reponse data"
if r.HTTPResponse != nil {
logBody := r.Service.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, logBody)
msg = string(dumpedBody)
} else if r.Error != nil {
msg = r.Error.Error()
}
r.Service.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.Service.ServiceName, r.Operation.Name, msg))
}

View File

@@ -0,0 +1,15 @@
package serviceinfo
import "github.com/aws/aws-sdk-go/aws"
// ServiceInfo wraps immutable data from the service.Service structure.
type ServiceInfo struct {
Config *aws.Config
ServiceName string
APIVersion string
Endpoint string
SigningName string
SigningRegion string
JSONVersion string
TargetPrefix string
}

View File

@@ -1,36 +1,10 @@
package aws package aws
import ( import (
"fmt"
"io" "io"
"time" "sync"
) )
// String converts a Go string into a string pointer.
func String(v string) *string {
return &v
}
// Boolean converts a Go bool into a boolean pointer.
func Boolean(v bool) *bool {
return &v
}
// Long converts a Go int64 into a long pointer.
func Long(v int64) *int64 {
return &v
}
// Double converts a Go float64 into a double pointer.
func Double(v float64) *float64 {
return &v
}
// Time converts a Go Time into a Time pointer
func Time(t time.Time) *time.Time {
return &t
}
// ReadSeekCloser wraps a io.Reader returning a ReaderSeakerCloser // ReadSeekCloser wraps a io.Reader returning a ReaderSeakerCloser
func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { func ReadSeekCloser(r io.Reader) ReaderSeekerCloser {
return ReaderSeekerCloser{r} return ReaderSeekerCloser{r}
@@ -81,51 +55,34 @@ func (r ReaderSeekerCloser) Close() error {
return nil return nil
} }
// A SettableBool provides a boolean value which includes the state if // A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface
// the value was set or unset. The set state is in addition to the value's // Can be used with the s3manager.Downloader to download content to a buffer
// value(true|false) // in memory. Safe to use concurrently.
type SettableBool struct { type WriteAtBuffer struct {
value bool buf []byte
set bool m sync.Mutex
} }
// SetBool returns a SettableBool with a value set // WriteAt writes a slice of bytes to a buffer starting at the position provided
func SetBool(value bool) SettableBool { // The number of bytes written will be returned, or error. Can overwrite previous
return SettableBool{value: value, set: true} // written slices if the write ats overlap.
} func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) {
b.m.Lock()
defer b.m.Unlock()
// Get returns the value. Will always be false if the SettableBool was not set. expLen := pos + int64(len(p))
func (b *SettableBool) Get() bool { if int64(len(b.buf)) < expLen {
if !b.set { newBuf := make([]byte, expLen)
return false copy(newBuf, b.buf)
b.buf = newBuf
} }
return b.value copy(b.buf[pos:], p)
return len(p), nil
} }
// Set sets the value and updates the state that the value has been set. // Bytes returns a slice of bytes written to the buffer.
func (b *SettableBool) Set(value bool) { func (b *WriteAtBuffer) Bytes() []byte {
b.value = value b.m.Lock()
b.set = true defer b.m.Unlock()
} return b.buf[:len(b.buf):len(b.buf)]
// IsSet returns if the value has been set
func (b *SettableBool) IsSet() bool {
return b.set
}
// Reset resets the state and value of the SettableBool to its initial default
// state of not set and zero value.
func (b *SettableBool) Reset() {
b.value = false
b.set = false
}
// String returns the string representation of the value if set. Zero if not set.
func (b *SettableBool) String() string {
return fmt.Sprintf("%t", b.Get())
}
// GoString returns the string representation of the SettableBool value and state
func (b *SettableBool) GoString() string {
return fmt.Sprintf("Bool{value:%t, set:%t}", b.value, b.set)
} }

View File

@@ -0,0 +1,56 @@
package aws
import (
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWriteAtBuffer(t *testing.T) {
b := &WriteAtBuffer{}
n, err := b.WriteAt([]byte{1}, 0)
assert.NoError(t, err)
assert.Equal(t, 1, n)
n, err = b.WriteAt([]byte{1, 1, 1}, 5)
assert.NoError(t, err)
assert.Equal(t, 3, n)
n, err = b.WriteAt([]byte{2}, 1)
assert.NoError(t, err)
assert.Equal(t, 1, n)
n, err = b.WriteAt([]byte{3}, 2)
assert.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, []byte{1, 2, 3, 0, 0, 1, 1, 1}, b.Bytes())
}
func BenchmarkWriteAtBuffer(b *testing.B) {
buf := &WriteAtBuffer{}
r := rand.New(rand.NewSource(1))
b.ResetTimer()
for i := 0; i < b.N; i++ {
to := r.Intn(10) * 4096
bs := make([]byte, to)
buf.WriteAt(bs, r.Int63n(10)*4096)
}
}
func BenchmarkWriteAtBufferParallel(b *testing.B) {
buf := &WriteAtBuffer{}
r := rand.New(rand.NewSource(1))
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
to := r.Intn(10) * 4096
bs := make([]byte, to)
buf.WriteAt(bs, r.Int63n(10)*4096)
}
})
}

View File

@@ -5,4 +5,4 @@ package aws
const SDKName = "aws-sdk-go" const SDKName = "aws-sdk-go"
// SDKVersion is the version of this SDK // SDKVersion is the version of this SDK
const SDKVersion = "0.6.0" const SDKVersion = "0.9.9"

View File

@@ -2,6 +2,7 @@
package endpoints package endpoints
//go:generate go run ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go //go:generate go run ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go
//go:generate gofmt -s -w endpoints_map.go
import "strings" import "strings"

View File

@@ -15,74 +15,74 @@ type endpointEntry struct {
var endpointsMap = endpointStruct{ var endpointsMap = endpointStruct{
Version: 2, Version: 2,
Endpoints: map[string]endpointEntry{ Endpoints: map[string]endpointEntry{
"*/*": endpointEntry{ "*/*": {
Endpoint: "{service}.{region}.amazonaws.com", Endpoint: "{service}.{region}.amazonaws.com",
}, },
"*/cloudfront": endpointEntry{ "*/cloudfront": {
Endpoint: "cloudfront.amazonaws.com", Endpoint: "cloudfront.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"*/cloudsearchdomain": endpointEntry{ "*/cloudsearchdomain": {
Endpoint: "", Endpoint: "",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"*/iam": endpointEntry{ "*/iam": {
Endpoint: "iam.amazonaws.com", Endpoint: "iam.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"*/importexport": endpointEntry{ "*/importexport": {
Endpoint: "importexport.amazonaws.com", Endpoint: "importexport.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"*/route53": endpointEntry{ "*/route53": {
Endpoint: "route53.amazonaws.com", Endpoint: "route53.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"*/sts": endpointEntry{ "*/sts": {
Endpoint: "sts.amazonaws.com", Endpoint: "sts.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"ap-northeast-1/s3": endpointEntry{ "ap-northeast-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"ap-southeast-1/s3": endpointEntry{ "ap-southeast-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"ap-southeast-2/s3": endpointEntry{ "ap-southeast-2/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"cn-north-1/*": endpointEntry{ "cn-north-1/*": {
Endpoint: "{service}.{region}.amazonaws.com.cn", Endpoint: "{service}.{region}.amazonaws.com.cn",
}, },
"eu-central-1/s3": endpointEntry{ "eu-central-1/s3": {
Endpoint: "{service}.{region}.amazonaws.com", Endpoint: "{service}.{region}.amazonaws.com",
}, },
"eu-west-1/s3": endpointEntry{ "eu-west-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"sa-east-1/s3": endpointEntry{ "sa-east-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"us-east-1/s3": endpointEntry{ "us-east-1/s3": {
Endpoint: "s3.amazonaws.com", Endpoint: "s3.amazonaws.com",
}, },
"us-east-1/sdb": endpointEntry{ "us-east-1/sdb": {
Endpoint: "sdb.amazonaws.com", Endpoint: "sdb.amazonaws.com",
SigningRegion: "us-east-1", SigningRegion: "us-east-1",
}, },
"us-gov-west-1/iam": endpointEntry{ "us-gov-west-1/iam": {
Endpoint: "iam.us-gov.amazonaws.com", Endpoint: "iam.us-gov.amazonaws.com",
}, },
"us-gov-west-1/s3": endpointEntry{ "us-gov-west-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"us-gov-west-1/sts": endpointEntry{ "us-gov-west-1/sts": {
Endpoint: "sts.us-gov-west-1.amazonaws.com", Endpoint: "sts.us-gov-west-1.amazonaws.com",
}, },
"us-west-1/s3": endpointEntry{ "us-west-1/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
"us-west-2/s3": endpointEntry{ "us-west-2/s3": {
Endpoint: "s3-{region}.amazonaws.com", Endpoint: "s3-{region}.amazonaws.com",
}, },
}, },

View File

@@ -6,19 +6,19 @@ package ec2query
import ( import (
"net/url" "net/url"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/protocol/query/queryutil" "github.com/aws/aws-sdk-go/internal/protocol/query/queryutil"
) )
// Build builds a request for the EC2 protocol. // Build builds a request for the EC2 protocol.
func Build(r *aws.Request) { func Build(r *request.Request) {
body := url.Values{ body := url.Values{
"Action": {r.Operation.Name}, "Action": {r.Operation.Name},
"Version": {r.Service.APIVersion}, "Version": {r.Service.APIVersion},
} }
if err := queryutil.Parse(body, r.Params, true); err != nil { if err := queryutil.Parse(body, r.Params, true); err != nil {
r.Error = apierr.New("Marshal", "failed encoding EC2 Query request", err) r.Error = awserr.New("SerializationError", "failed encoding EC2 Query request", err)
} }
if r.ExpireTime == 0 { if r.ExpireTime == 0 {

View File

@@ -1,10 +1,6 @@
package ec2query_test package ec2query_test
import ( import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/internal/protocol/ec2query"
"github.com/aws/aws-sdk-go/internal/signer/v4"
"bytes" "bytes"
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
@@ -15,7 +11,14 @@ import (
"testing" "testing"
"time" "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/ec2query"
"github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/internal/signer/v4"
"github.com/aws/aws-sdk-go/internal/util" "github.com/aws/aws-sdk-go/internal/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -31,17 +34,18 @@ var _ = util.Trim("")
var _ = url.Values{} var _ = url.Values{}
var _ = io.EOF var _ = io.EOF
// InputService1ProtocolTest is a client for InputService1ProtocolTest.
type InputService1ProtocolTest struct { type InputService1ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService1ProtocolTest client. // New returns a new InputService1ProtocolTest client.
func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice1protocoltest", ServiceName: "inputservice1protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -57,38 +61,47 @@ func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest
// newRequest creates a new request for a InputService1ProtocolTest operation and runs any // newRequest creates a new request for a InputService1ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. const opInputService1TestCaseOperation1 = "OperationName"
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) {
if opInputService1TestCaseOperation1 == nil { // InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation.
opInputService1TestCaseOperation1 = &aws.Operation{ func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService1TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService1TestShapeInputShape{} input = &InputService1TestShapeInputService1TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService1TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService1TestShapeInputService1TestCaseOperation1Output{} output = &InputService1TestShapeInputService1TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) {
req, out := c.InputService1TestCaseOperation1Request(input) req, out := c.InputService1TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService1TestCaseOperation1 *aws.Operation type InputService1TestShapeInputService1TestCaseOperation1Input struct {
Bar *string `type:"string"`
Foo *string `type:"string"`
metadataInputService1TestShapeInputService1TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService1TestShapeInputService1TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService1TestShapeInputService1TestCaseOperation1Output struct { type InputService1TestShapeInputService1TestCaseOperation1Output struct {
metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"`
@@ -98,29 +111,18 @@ type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService1TestShapeInputShape struct {
Bar *string `type:"string"`
Foo *string `type:"string"`
metadataInputService1TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService1TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService2ProtocolTest is a client for InputService2ProtocolTest.
type InputService2ProtocolTest struct { type InputService2ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService2ProtocolTest client. // New returns a new InputService2ProtocolTest client.
func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice2protocoltest", ServiceName: "inputservice2protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -136,38 +138,49 @@ func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest
// newRequest creates a new request for a InputService2ProtocolTest operation and runs any // newRequest creates a new request for a InputService2ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. const opInputService2TestCaseOperation1 = "OperationName"
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *aws.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) {
if opInputService2TestCaseOperation1 == nil { // InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation.
opInputService2TestCaseOperation1 = &aws.Operation{ func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService2TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService2TestShapeInputShape{} input = &InputService2TestShapeInputService2TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService2TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService2TestShapeInputService2TestCaseOperation1Output{} output = &InputService2TestShapeInputService2TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) {
req, out := c.InputService2TestCaseOperation1Request(input) req, out := c.InputService2TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService2TestCaseOperation1 *aws.Operation type InputService2TestShapeInputService2TestCaseOperation1Input struct {
Bar *string `locationName:"barLocationName" type:"string"`
Foo *string `type:"string"`
Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"`
metadataInputService2TestShapeInputService2TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService2TestShapeInputService2TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService2TestShapeInputService2TestCaseOperation1Output struct { type InputService2TestShapeInputService2TestCaseOperation1Output struct {
metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"`
@@ -177,31 +190,18 @@ type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService2TestShapeInputShape struct {
Bar *string `locationName:"barLocationName" type:"string"`
Foo *string `type:"string"`
Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"`
metadataInputService2TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService2TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService3ProtocolTest is a client for InputService3ProtocolTest.
type InputService3ProtocolTest struct { type InputService3ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService3ProtocolTest client. // New returns a new InputService3ProtocolTest client.
func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice3protocoltest", ServiceName: "inputservice3protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -217,38 +217,45 @@ func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest
// newRequest creates a new request for a InputService3ProtocolTest operation and runs any // newRequest creates a new request for a InputService3ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. const opInputService3TestCaseOperation1 = "OperationName"
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) {
if opInputService3TestCaseOperation1 == nil { // InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation.
opInputService3TestCaseOperation1 = &aws.Operation{ func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService3TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService3TestShapeInputShape{} input = &InputService3TestShapeInputService3TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService3TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService3TestShapeInputService3TestCaseOperation1Output{} output = &InputService3TestShapeInputService3TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) {
req, out := c.InputService3TestCaseOperation1Request(input) req, out := c.InputService3TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService3TestCaseOperation1 *aws.Operation type InputService3TestShapeInputService3TestCaseOperation1Input struct {
StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"`
metadataInputService3TestShapeInputService3TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService3TestShapeInputService3TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService3TestShapeInputService3TestCaseOperation1Output struct { type InputService3TestShapeInputService3TestCaseOperation1Output struct {
metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"`
@@ -258,16 +265,6 @@ type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService3TestShapeInputShape struct {
StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"`
metadataInputService3TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService3TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService3TestShapeStructType struct { type InputService3TestShapeStructType struct {
ScalarArg *string `locationName:"Scalar" type:"string"` ScalarArg *string `locationName:"Scalar" type:"string"`
@@ -278,17 +275,18 @@ type metadataInputService3TestShapeStructType struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// InputService4ProtocolTest is a client for InputService4ProtocolTest.
type InputService4ProtocolTest struct { type InputService4ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService4ProtocolTest client. // New returns a new InputService4ProtocolTest client.
func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice4protocoltest", ServiceName: "inputservice4protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -304,38 +302,45 @@ func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest
// newRequest creates a new request for a InputService4ProtocolTest operation and runs any // newRequest creates a new request for a InputService4ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. const opInputService4TestCaseOperation1 = "OperationName"
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) {
if opInputService4TestCaseOperation1 == nil { // InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation.
opInputService4TestCaseOperation1 = &aws.Operation{ func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService4TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService4TestShapeInputShape{} input = &InputService4TestShapeInputService4TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService4TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService4TestShapeInputService4TestCaseOperation1Output{} output = &InputService4TestShapeInputService4TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) {
req, out := c.InputService4TestCaseOperation1Request(input) req, out := c.InputService4TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService4TestCaseOperation1 *aws.Operation type InputService4TestShapeInputService4TestCaseOperation1Input struct {
ListArg []*string `type:"list"`
metadataInputService4TestShapeInputService4TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService4TestShapeInputService4TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService4TestShapeInputService4TestCaseOperation1Output struct { type InputService4TestShapeInputService4TestCaseOperation1Output struct {
metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"`
@@ -345,27 +350,18 @@ type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService4TestShapeInputShape struct {
ListArg []*string `type:"list"`
metadataInputService4TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService4TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService5ProtocolTest is a client for InputService5ProtocolTest.
type InputService5ProtocolTest struct { type InputService5ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService5ProtocolTest client. // New returns a new InputService5ProtocolTest client.
func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice5protocoltest", ServiceName: "inputservice5protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -381,38 +377,45 @@ func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest
// newRequest creates a new request for a InputService5ProtocolTest operation and runs any // newRequest creates a new request for a InputService5ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. const opInputService5TestCaseOperation1 = "OperationName"
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) {
if opInputService5TestCaseOperation1 == nil { // InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation.
opInputService5TestCaseOperation1 = &aws.Operation{ func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService5TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService5TestShapeInputShape{} input = &InputService5TestShapeInputService5TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService5TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService5TestShapeInputService5TestCaseOperation1Output{} output = &InputService5TestShapeInputService5TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) {
req, out := c.InputService5TestCaseOperation1Request(input) req, out := c.InputService5TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService5TestCaseOperation1 *aws.Operation type InputService5TestShapeInputService5TestCaseOperation1Input struct {
ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"`
metadataInputService5TestShapeInputService5TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService5TestShapeInputService5TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService5TestShapeInputService5TestCaseOperation1Output struct { type InputService5TestShapeInputService5TestCaseOperation1Output struct {
metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"`
@@ -422,27 +425,18 @@ type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService5TestShapeInputShape struct {
ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"`
metadataInputService5TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService5TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService6ProtocolTest is a client for InputService6ProtocolTest.
type InputService6ProtocolTest struct { type InputService6ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService6ProtocolTest client. // New returns a new InputService6ProtocolTest client.
func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice6protocoltest", ServiceName: "inputservice6protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -458,38 +452,45 @@ func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest
// newRequest creates a new request for a InputService6ProtocolTest operation and runs any // newRequest creates a new request for a InputService6ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. const opInputService6TestCaseOperation1 = "OperationName"
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *aws.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) {
if opInputService6TestCaseOperation1 == nil { // InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation.
opInputService6TestCaseOperation1 = &aws.Operation{ func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService6TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService6TestShapeInputShape{} input = &InputService6TestShapeInputService6TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService6TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService6TestShapeInputService6TestCaseOperation1Output{} output = &InputService6TestShapeInputService6TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) {
req, out := c.InputService6TestCaseOperation1Request(input) req, out := c.InputService6TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService6TestCaseOperation1 *aws.Operation type InputService6TestShapeInputService6TestCaseOperation1Input struct {
ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"`
metadataInputService6TestShapeInputService6TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService6TestShapeInputService6TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService6TestShapeInputService6TestCaseOperation1Output struct { type InputService6TestShapeInputService6TestCaseOperation1Output struct {
metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"`
@@ -499,27 +500,18 @@ type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService6TestShapeInputShape struct {
ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"`
metadataInputService6TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService6TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService7ProtocolTest is a client for InputService7ProtocolTest.
type InputService7ProtocolTest struct { type InputService7ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService7ProtocolTest client. // New returns a new InputService7ProtocolTest client.
func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice7protocoltest", ServiceName: "inputservice7protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -535,38 +527,45 @@ func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest
// newRequest creates a new request for a InputService7ProtocolTest operation and runs any // newRequest creates a new request for a InputService7ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. const opInputService7TestCaseOperation1 = "OperationName"
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *aws.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) {
if opInputService7TestCaseOperation1 == nil { // InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation.
opInputService7TestCaseOperation1 = &aws.Operation{ func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService7TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService7TestShapeInputShape{} input = &InputService7TestShapeInputService7TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService7TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService7TestShapeInputService7TestCaseOperation1Output{} output = &InputService7TestShapeInputService7TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) {
req, out := c.InputService7TestCaseOperation1Request(input) req, out := c.InputService7TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService7TestCaseOperation1 *aws.Operation type InputService7TestShapeInputService7TestCaseOperation1Input struct {
BlobArg []byte `type:"blob"`
metadataInputService7TestShapeInputService7TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService7TestShapeInputService7TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService7TestShapeInputService7TestCaseOperation1Output struct { type InputService7TestShapeInputService7TestCaseOperation1Output struct {
metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"`
@@ -576,27 +575,18 @@ type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService7TestShapeInputShape struct {
BlobArg []byte `type:"blob"`
metadataInputService7TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService7TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService8ProtocolTest is a client for InputService8ProtocolTest.
type InputService8ProtocolTest struct { type InputService8ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new InputService8ProtocolTest client. // New returns a new InputService8ProtocolTest client.
func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "inputservice8protocoltest", ServiceName: "inputservice8protocoltest",
APIVersion: "2014-01-01", APIVersion: "2014-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -612,38 +602,45 @@ func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest
// newRequest creates a new request for a InputService8ProtocolTest operation and runs any // newRequest creates a new request for a InputService8ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. const opInputService8TestCaseOperation1 = "OperationName"
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *aws.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) {
if opInputService8TestCaseOperation1 == nil { // InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation.
opInputService8TestCaseOperation1 = &aws.Operation{ func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opInputService8TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &InputService8TestShapeInputShape{} input = &InputService8TestShapeInputService8TestCaseOperation1Input{}
} }
req = c.newRequest(opInputService8TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &InputService8TestShapeInputService8TestCaseOperation1Output{} output = &InputService8TestShapeInputService8TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) {
req, out := c.InputService8TestCaseOperation1Request(input) req, out := c.InputService8TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opInputService8TestCaseOperation1 *aws.Operation type InputService8TestShapeInputService8TestCaseOperation1Input struct {
TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"`
metadataInputService8TestShapeInputService8TestCaseOperation1Input `json:"-" xml:"-"`
}
type metadataInputService8TestShapeInputService8TestCaseOperation1Input struct {
SDKShapeTraits bool `type:"structure"`
}
type InputService8TestShapeInputService8TestCaseOperation1Output struct { type InputService8TestShapeInputService8TestCaseOperation1Output struct {
metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"`
@@ -653,16 +650,6 @@ type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type InputService8TestShapeInputShape struct {
TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"`
metadataInputService8TestShapeInputShape `json:"-" xml:"-"`
}
type metadataInputService8TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// //
// Tests begin here // Tests begin here
// //
@@ -671,7 +658,7 @@ func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) {
svc := NewInputService1ProtocolTest(nil) svc := NewInputService1ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService1TestShapeInputShape{ input := &InputService1TestShapeInputService1TestCaseOperation1Input{
Bar: aws.String("val2"), Bar: aws.String("val2"),
Foo: aws.String("val1"), Foo: aws.String("val1"),
} }
@@ -698,7 +685,7 @@ func TestInputService2ProtocolTestStructureWithLocationNameAndQueryNameAppliedTo
svc := NewInputService2ProtocolTest(nil) svc := NewInputService2ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService2TestShapeInputShape{ input := &InputService2TestShapeInputService2TestCaseOperation1Input{
Bar: aws.String("val2"), Bar: aws.String("val2"),
Foo: aws.String("val1"), Foo: aws.String("val1"),
Yuck: aws.String("val3"), Yuck: aws.String("val3"),
@@ -726,7 +713,7 @@ func TestInputService3ProtocolTestNestedStructureMembersCase1(t *testing.T) {
svc := NewInputService3ProtocolTest(nil) svc := NewInputService3ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService3TestShapeInputShape{ input := &InputService3TestShapeInputService3TestCaseOperation1Input{
StructArg: &InputService3TestShapeStructType{ StructArg: &InputService3TestShapeStructType{
ScalarArg: aws.String("foo"), ScalarArg: aws.String("foo"),
}, },
@@ -754,7 +741,7 @@ func TestInputService4ProtocolTestListTypesCase1(t *testing.T) {
svc := NewInputService4ProtocolTest(nil) svc := NewInputService4ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService4TestShapeInputShape{ input := &InputService4TestShapeInputService4TestCaseOperation1Input{
ListArg: []*string{ ListArg: []*string{
aws.String("foo"), aws.String("foo"),
aws.String("bar"), aws.String("bar"),
@@ -784,7 +771,7 @@ func TestInputService5ProtocolTestListWithLocationNameAppliedToMemberCase1(t *te
svc := NewInputService5ProtocolTest(nil) svc := NewInputService5ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService5TestShapeInputShape{ input := &InputService5TestShapeInputService5TestCaseOperation1Input{
ListArg: []*string{ ListArg: []*string{
aws.String("a"), aws.String("a"),
aws.String("b"), aws.String("b"),
@@ -814,7 +801,7 @@ func TestInputService6ProtocolTestListWithLocationNameAndQueryNameCase1(t *testi
svc := NewInputService6ProtocolTest(nil) svc := NewInputService6ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService6TestShapeInputShape{ input := &InputService6TestShapeInputService6TestCaseOperation1Input{
ListArg: []*string{ ListArg: []*string{
aws.String("a"), aws.String("a"),
aws.String("b"), aws.String("b"),
@@ -844,7 +831,7 @@ func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) {
svc := NewInputService7ProtocolTest(nil) svc := NewInputService7ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService7TestShapeInputShape{ input := &InputService7TestShapeInputService7TestCaseOperation1Input{
BlobArg: []byte("foo"), BlobArg: []byte("foo"),
} }
req, _ := svc.InputService7TestCaseOperation1Request(input) req, _ := svc.InputService7TestCaseOperation1Request(input)
@@ -870,7 +857,7 @@ func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) {
svc := NewInputService8ProtocolTest(nil) svc := NewInputService8ProtocolTest(nil)
svc.Endpoint = "https://test" svc.Endpoint = "https://test"
input := &InputService8TestShapeInputShape{ input := &InputService8TestShapeInputService8TestCaseOperation1Input{
TimeArg: aws.Time(time.Unix(1422172800, 0)), TimeArg: aws.Time(time.Unix(1422172800, 0)),
} }
req, _ := svc.InputService8TestCaseOperation1Request(input) req, _ := svc.InputService8TestCaseOperation1Request(input)

View File

@@ -6,26 +6,26 @@ import (
"encoding/xml" "encoding/xml"
"io" "io"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil"
) )
// Unmarshal unmarshals a response body for the EC2 protocol. // Unmarshal unmarshals a response body for the EC2 protocol.
func Unmarshal(r *aws.Request) { func Unmarshal(r *request.Request) {
defer r.HTTPResponse.Body.Close() defer r.HTTPResponse.Body.Close()
if r.DataFilled() { if r.DataFilled() {
decoder := xml.NewDecoder(r.HTTPResponse.Body) decoder := xml.NewDecoder(r.HTTPResponse.Body)
err := xmlutil.UnmarshalXML(r.Data, decoder, "") err := xmlutil.UnmarshalXML(r.Data, decoder, "")
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed decoding EC2 Query response", err) r.Error = awserr.New("SerializationError", "failed decoding EC2 Query response", err)
return return
} }
} }
} }
// UnmarshalMeta unmarshals response headers for the EC2 protocol. // UnmarshalMeta unmarshals response headers for the EC2 protocol.
func UnmarshalMeta(r *aws.Request) { func UnmarshalMeta(r *request.Request) {
// TODO implement unmarshaling of request IDs // TODO implement unmarshaling of request IDs
} }
@@ -37,16 +37,16 @@ type xmlErrorResponse struct {
} }
// UnmarshalError unmarshals a response error for the EC2 protocol. // UnmarshalError unmarshals a response error for the EC2 protocol.
func UnmarshalError(r *aws.Request) { func UnmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close() defer r.HTTPResponse.Body.Close()
resp := &xmlErrorResponse{} resp := &xmlErrorResponse{}
err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
r.Error = apierr.New("Unmarshal", "failed decoding EC2 Query error response", err) r.Error = awserr.New("SerializationError", "failed decoding EC2 Query error response", err)
} else { } else {
r.Error = apierr.NewRequestError( r.Error = awserr.NewRequestFailure(
apierr.New(resp.Code, resp.Message, nil), awserr.New(resp.Code, resp.Message, nil),
r.HTTPResponse.StatusCode, r.HTTPResponse.StatusCode,
resp.RequestID, resp.RequestID,
) )

View File

@@ -1,10 +1,6 @@
package ec2query_test package ec2query_test
import ( import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/internal/protocol/ec2query"
"github.com/aws/aws-sdk-go/internal/signer/v4"
"bytes" "bytes"
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
@@ -15,7 +11,14 @@ import (
"testing" "testing"
"time" "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/ec2query"
"github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil"
"github.com/aws/aws-sdk-go/internal/signer/v4"
"github.com/aws/aws-sdk-go/internal/util" "github.com/aws/aws-sdk-go/internal/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -31,17 +34,18 @@ var _ = util.Trim("")
var _ = url.Values{} var _ = url.Values{}
var _ = io.EOF var _ = io.EOF
// OutputService1ProtocolTest is a client for OutputService1ProtocolTest.
type OutputService1ProtocolTest struct { type OutputService1ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService1ProtocolTest client. // New returns a new OutputService1ProtocolTest client.
func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice1protocoltest", ServiceName: "outputservice1protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -57,39 +61,36 @@ func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTe
// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any // newRequest creates a new request for a OutputService1ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. const opOutputService1TestCaseOperation1 = "OperationName"
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) {
if opOutputService1TestCaseOperation1 == nil { // OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation.
opOutputService1TestCaseOperation1 = &aws.Operation{ func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService1TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService1TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService1TestShapeOutputShape{} output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputShape, error) { func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input) req, out := c.OutputService1TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService1TestCaseOperation1 *aws.Operation
type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { type OutputService1TestShapeOutputService1TestCaseOperation1Input struct {
metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -98,7 +99,7 @@ type metadataOutputService1TestShapeOutputService1TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService1TestShapeOutputShape struct { type OutputService1TestShapeOutputService1TestCaseOperation1Output struct {
Char *string `type:"character"` Char *string `type:"character"`
Double *float64 `type:"double"` Double *float64 `type:"double"`
@@ -115,24 +116,25 @@ type OutputService1TestShapeOutputShape struct {
TrueBool *bool `type:"boolean"` TrueBool *bool `type:"boolean"`
metadataOutputService1TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService1TestShapeOutputService1TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService1TestShapeOutputShape struct { type metadataOutputService1TestShapeOutputService1TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService2ProtocolTest is a client for OutputService2ProtocolTest.
type OutputService2ProtocolTest struct { type OutputService2ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService2ProtocolTest client. // New returns a new OutputService2ProtocolTest client.
func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice2protocoltest", ServiceName: "outputservice2protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -148,39 +150,36 @@ func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTe
// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any // newRequest creates a new request for a OutputService2ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. const opOutputService2TestCaseOperation1 = "OperationName"
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *aws.Request, output *OutputService2TestShapeOutputShape) {
if opOutputService2TestCaseOperation1 == nil { // OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation.
opOutputService2TestCaseOperation1 = &aws.Operation{ func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService2TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService2TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService2TestShapeOutputShape{} output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputShape, error) { func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input) req, out := c.OutputService2TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService2TestCaseOperation1 *aws.Operation
type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { type OutputService2TestShapeOutputService2TestCaseOperation1Input struct {
metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -189,27 +188,28 @@ type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService2TestShapeOutputShape struct { type OutputService2TestShapeOutputService2TestCaseOperation1Output struct {
Blob []byte `type:"blob"` Blob []byte `type:"blob"`
metadataOutputService2TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService2TestShapeOutputService2TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService2TestShapeOutputShape struct { type metadataOutputService2TestShapeOutputService2TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService3ProtocolTest is a client for OutputService3ProtocolTest.
type OutputService3ProtocolTest struct { type OutputService3ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService3ProtocolTest client. // New returns a new OutputService3ProtocolTest client.
func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice3protocoltest", ServiceName: "outputservice3protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -225,39 +225,36 @@ func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTe
// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any // newRequest creates a new request for a OutputService3ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. const opOutputService3TestCaseOperation1 = "OperationName"
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *aws.Request, output *OutputService3TestShapeOutputShape) {
if opOutputService3TestCaseOperation1 == nil { // OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation.
opOutputService3TestCaseOperation1 = &aws.Operation{ func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService3TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService3TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService3TestShapeOutputShape{} output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputShape, error) { func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input) req, out := c.OutputService3TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService3TestCaseOperation1 *aws.Operation
type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { type OutputService3TestShapeOutputService3TestCaseOperation1Input struct {
metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -266,27 +263,28 @@ type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService3TestShapeOutputShape struct { type OutputService3TestShapeOutputService3TestCaseOperation1Output struct {
ListMember []*string `type:"list"` ListMember []*string `type:"list"`
metadataOutputService3TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService3TestShapeOutputService3TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService3TestShapeOutputShape struct { type metadataOutputService3TestShapeOutputService3TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService4ProtocolTest is a client for OutputService4ProtocolTest.
type OutputService4ProtocolTest struct { type OutputService4ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService4ProtocolTest client. // New returns a new OutputService4ProtocolTest client.
func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice4protocoltest", ServiceName: "outputservice4protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -302,39 +300,36 @@ func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTe
// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any // newRequest creates a new request for a OutputService4ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. const opOutputService4TestCaseOperation1 = "OperationName"
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *aws.Request, output *OutputService4TestShapeOutputShape) {
if opOutputService4TestCaseOperation1 == nil { // OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation.
opOutputService4TestCaseOperation1 = &aws.Operation{ func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService4TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService4TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService4TestShapeOutputShape{} output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputShape, error) { func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input) req, out := c.OutputService4TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService4TestCaseOperation1 *aws.Operation
type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { type OutputService4TestShapeOutputService4TestCaseOperation1Input struct {
metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -343,27 +338,28 @@ type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService4TestShapeOutputShape struct { type OutputService4TestShapeOutputService4TestCaseOperation1Output struct {
ListMember []*string `locationNameList:"item" type:"list"` ListMember []*string `locationNameList:"item" type:"list"`
metadataOutputService4TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService4TestShapeOutputService4TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService4TestShapeOutputShape struct { type metadataOutputService4TestShapeOutputService4TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService5ProtocolTest is a client for OutputService5ProtocolTest.
type OutputService5ProtocolTest struct { type OutputService5ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService5ProtocolTest client. // New returns a new OutputService5ProtocolTest client.
func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice5protocoltest", ServiceName: "outputservice5protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -379,39 +375,36 @@ func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTe
// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any // newRequest creates a new request for a OutputService5ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. const opOutputService5TestCaseOperation1 = "OperationName"
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *aws.Request, output *OutputService5TestShapeOutputShape) {
if opOutputService5TestCaseOperation1 == nil { // OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation.
opOutputService5TestCaseOperation1 = &aws.Operation{ func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService5TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService5TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService5TestShapeOutputShape{} output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputShape, error) { func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input) req, out := c.OutputService5TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService5TestCaseOperation1 *aws.Operation
type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { type OutputService5TestShapeOutputService5TestCaseOperation1Input struct {
metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -420,27 +413,28 @@ type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService5TestShapeOutputShape struct { type OutputService5TestShapeOutputService5TestCaseOperation1Output struct {
ListMember []*string `type:"list" flattened:"true"` ListMember []*string `type:"list" flattened:"true"`
metadataOutputService5TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService5TestShapeOutputService5TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService5TestShapeOutputShape struct { type metadataOutputService5TestShapeOutputService5TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService6ProtocolTest is a client for OutputService6ProtocolTest.
type OutputService6ProtocolTest struct { type OutputService6ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService6ProtocolTest client. // New returns a new OutputService6ProtocolTest client.
func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice6protocoltest", ServiceName: "outputservice6protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -456,39 +450,36 @@ func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTe
// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any // newRequest creates a new request for a OutputService6ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. const opOutputService6TestCaseOperation1 = "OperationName"
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *aws.Request, output *OutputService6TestShapeOutputShape) {
if opOutputService6TestCaseOperation1 == nil { // OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation.
opOutputService6TestCaseOperation1 = &aws.Operation{ func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService6TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService6TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService6TestShapeOutputShape{} output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputShape, error) { func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input) req, out := c.OutputService6TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService6TestCaseOperation1 *aws.Operation
type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { type OutputService6TestShapeOutputService6TestCaseOperation1Input struct {
metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -497,13 +488,13 @@ type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService6TestShapeOutputShape struct { type OutputService6TestShapeOutputService6TestCaseOperation1Output struct {
Map map[string]*OutputService6TestShapeStructureType `type:"map"` Map map[string]*OutputService6TestShapeStructureType `type:"map"`
metadataOutputService6TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService6TestShapeOutputService6TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService6TestShapeOutputShape struct { type metadataOutputService6TestShapeOutputService6TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
@@ -517,17 +508,18 @@ type metadataOutputService6TestShapeStructureType struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService7ProtocolTest is a client for OutputService7ProtocolTest.
type OutputService7ProtocolTest struct { type OutputService7ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService7ProtocolTest client. // New returns a new OutputService7ProtocolTest client.
func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice7protocoltest", ServiceName: "outputservice7protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -543,39 +535,36 @@ func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTe
// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any // newRequest creates a new request for a OutputService7ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. const opOutputService7TestCaseOperation1 = "OperationName"
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *aws.Request, output *OutputService7TestShapeOutputShape) {
if opOutputService7TestCaseOperation1 == nil { // OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation.
opOutputService7TestCaseOperation1 = &aws.Operation{ func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService7TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService7TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService7TestShapeOutputShape{} output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputShape, error) { func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input) req, out := c.OutputService7TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService7TestCaseOperation1 *aws.Operation
type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { type OutputService7TestShapeOutputService7TestCaseOperation1Input struct {
metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -584,27 +573,28 @@ type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService7TestShapeOutputShape struct { type OutputService7TestShapeOutputService7TestCaseOperation1Output struct {
Map map[string]*string `type:"map" flattened:"true"` Map map[string]*string `type:"map" flattened:"true"`
metadataOutputService7TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService7TestShapeOutputService7TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService7TestShapeOutputShape struct { type metadataOutputService7TestShapeOutputService7TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
// OutputService8ProtocolTest is a client for OutputService8ProtocolTest.
type OutputService8ProtocolTest struct { type OutputService8ProtocolTest struct {
*aws.Service *service.Service
} }
// New returns a new OutputService8ProtocolTest client. // New returns a new OutputService8ProtocolTest client.
func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "outputservice8protocoltest", ServiceName: "outputservice8protocoltest",
APIVersion: "", APIVersion: "",
},
} }
service.Initialize() service.Initialize()
@@ -620,39 +610,36 @@ func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTe
// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any // newRequest creates a new request for a OutputService8ProtocolTest operation and runs any
// custom request initialization. // custom request initialization.
func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
return req return req
} }
// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. const opOutputService8TestCaseOperation1 = "OperationName"
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *aws.Request, output *OutputService8TestShapeOutputShape) {
if opOutputService8TestCaseOperation1 == nil { // OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation.
opOutputService8TestCaseOperation1 = &aws.Operation{ func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) {
Name: "OperationName", op := &request.Operation{
} Name: opOutputService8TestCaseOperation1,
} }
if input == nil { if input == nil {
input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{}
} }
req = c.newRequest(opOutputService8TestCaseOperation1, input, output) req = c.newRequest(op, input, output)
output = &OutputService8TestShapeOutputShape{} output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{}
req.Data = output req.Data = output
return return
} }
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputShape, error) { func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input) req, out := c.OutputService8TestCaseOperation1Request(input)
err := req.Send() err := req.Send()
return out, err return out, err
} }
var opOutputService8TestCaseOperation1 *aws.Operation
type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { type OutputService8TestShapeOutputService8TestCaseOperation1Input struct {
metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"`
} }
@@ -661,13 +648,13 @@ type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }
type OutputService8TestShapeOutputShape struct { type OutputService8TestShapeOutputService8TestCaseOperation1Output struct {
Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"`
metadataOutputService8TestShapeOutputShape `json:"-" xml:"-"` metadataOutputService8TestShapeOutputService8TestCaseOperation1Output `json:"-" xml:"-"`
} }
type metadataOutputService8TestShapeOutputShape struct { type metadataOutputService8TestShapeOutputService8TestCaseOperation1Output struct {
SDKShapeTraits bool `type:"structure"` SDKShapeTraits bool `type:"structure"`
} }

View File

@@ -6,19 +6,19 @@ package query
import ( import (
"net/url" "net/url"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/protocol/query/queryutil" "github.com/aws/aws-sdk-go/internal/protocol/query/queryutil"
) )
// Build builds a request for an AWS Query service. // Build builds a request for an AWS Query service.
func Build(r *aws.Request) { func Build(r *request.Request) {
body := url.Values{ body := url.Values{
"Action": {r.Operation.Name}, "Action": {r.Operation.Name},
"Version": {r.Service.APIVersion}, "Version": {r.Service.APIVersion},
} }
if err := queryutil.Parse(body, r.Params, false); err != nil { if err := queryutil.Parse(body, r.Params, false); err != nil {
r.Error = apierr.New("Marshal", "failed encoding Query request", err) r.Error = awserr.New("SerializationError", "failed encoding Query request", err)
return return
} }

File diff suppressed because it is too large Load Diff

View File

@@ -5,25 +5,25 @@ package query
import ( import (
"encoding/xml" "encoding/xml"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil"
) )
// Unmarshal unmarshals a response for an AWS Query service. // Unmarshal unmarshals a response for an AWS Query service.
func Unmarshal(r *aws.Request) { func Unmarshal(r *request.Request) {
defer r.HTTPResponse.Body.Close() defer r.HTTPResponse.Body.Close()
if r.DataFilled() { if r.DataFilled() {
decoder := xml.NewDecoder(r.HTTPResponse.Body) decoder := xml.NewDecoder(r.HTTPResponse.Body)
err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result")
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed decoding Query response", err) r.Error = awserr.New("SerializationError", "failed decoding Query response", err)
return return
} }
} }
} }
// UnmarshalMeta unmarshals header response values for an AWS Query service. // UnmarshalMeta unmarshals header response values for an AWS Query service.
func UnmarshalMeta(r *aws.Request) { func UnmarshalMeta(r *request.Request) {
// TODO implement unmarshaling of request IDs // TODO implement unmarshaling of request IDs
} }

View File

@@ -4,8 +4,8 @@ import (
"encoding/xml" "encoding/xml"
"io" "io"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
) )
type xmlErrorResponse struct { type xmlErrorResponse struct {
@@ -16,16 +16,16 @@ type xmlErrorResponse struct {
} }
// UnmarshalError unmarshals an error response for an AWS Query service. // UnmarshalError unmarshals an error response for an AWS Query service.
func UnmarshalError(r *aws.Request) { func UnmarshalError(r *request.Request) {
defer r.HTTPResponse.Body.Close() defer r.HTTPResponse.Body.Close()
resp := &xmlErrorResponse{} resp := &xmlErrorResponse{}
err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
r.Error = apierr.New("Unmarshal", "failed to decode query XML error response", err) r.Error = awserr.New("SerializationError", "failed to decode query XML error response", err)
} else { } else {
r.Error = apierr.NewRequestError( r.Error = awserr.NewRequestFailure(
apierr.New(resp.Code, resp.Message, nil), awserr.New(resp.Code, resp.Message, nil),
r.HTTPResponse.StatusCode, r.HTTPResponse.StatusCode,
resp.RequestID, resp.RequestID,
) )

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
// Package rest provides RESTful serialisation of AWS requests and responses. // Package rest provides RESTful serialization of AWS requests and responses.
package rest package rest
import ( import (
@@ -13,8 +13,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/request"
) )
// RFC822 returns an RFC822 formatted timestamp for AWS protocols // RFC822 returns an RFC822 formatted timestamp for AWS protocols
@@ -37,7 +37,7 @@ func init() {
} }
// Build builds the REST component of a service request. // Build builds the REST component of a service request.
func Build(r *aws.Request) { func Build(r *request.Request) {
if r.ParamsFilled() { if r.ParamsFilled() {
v := reflect.ValueOf(r.Params).Elem() v := reflect.ValueOf(r.Params).Elem()
buildLocationElements(r, v) buildLocationElements(r, v)
@@ -45,7 +45,7 @@ func Build(r *aws.Request) {
} }
} }
func buildLocationElements(r *aws.Request, v reflect.Value) { func buildLocationElements(r *request.Request, v reflect.Value) {
query := r.HTTPRequest.URL.Query() query := r.HTTPRequest.URL.Query()
for i := 0; i < v.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
@@ -87,7 +87,7 @@ func buildLocationElements(r *aws.Request, v reflect.Value) {
updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path) updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
} }
func buildBody(r *aws.Request, v reflect.Value) { func buildBody(r *request.Request, v reflect.Value) {
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" { if payloadName := field.Tag.Get("payload"); payloadName != "" {
pfield, _ := v.Type().FieldByName(payloadName) pfield, _ := v.Type().FieldByName(payloadName)
@@ -102,7 +102,7 @@ func buildBody(r *aws.Request, v reflect.Value) {
case string: case string:
r.SetStringBody(reader) r.SetStringBody(reader)
default: default:
r.Error = apierr.New("Marshal", r.Error = awserr.New("SerializationError",
"failed to encode REST request", "failed to encode REST request",
fmt.Errorf("unknown payload type %s", payload.Type())) fmt.Errorf("unknown payload type %s", payload.Type()))
} }
@@ -112,30 +112,30 @@ func buildBody(r *aws.Request, v reflect.Value) {
} }
} }
func buildHeader(r *aws.Request, v reflect.Value, name string) { func buildHeader(r *request.Request, v reflect.Value, name string) {
str, err := convertType(v) str, err := convertType(v)
if err != nil { if err != nil {
r.Error = apierr.New("Marshal", "failed to encode REST request", err) r.Error = awserr.New("SerializationError", "failed to encode REST request", err)
} else if str != nil { } else if str != nil {
r.HTTPRequest.Header.Add(name, *str) r.HTTPRequest.Header.Add(name, *str)
} }
} }
func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) { func buildHeaderMap(r *request.Request, v reflect.Value, prefix string) {
for _, key := range v.MapKeys() { for _, key := range v.MapKeys() {
str, err := convertType(v.MapIndex(key)) str, err := convertType(v.MapIndex(key))
if err != nil { if err != nil {
r.Error = apierr.New("Marshal", "failed to encode REST request", err) r.Error = awserr.New("SerializationError", "failed to encode REST request", err)
} else if str != nil { } else if str != nil {
r.HTTPRequest.Header.Add(prefix+key.String(), *str) r.HTTPRequest.Header.Add(prefix+key.String(), *str)
} }
} }
} }
func buildURI(r *aws.Request, v reflect.Value, name string) { func buildURI(r *request.Request, v reflect.Value, name string) {
value, err := convertType(v) value, err := convertType(v)
if err != nil { if err != nil {
r.Error = apierr.New("Marshal", "failed to encode REST request", err) r.Error = awserr.New("SerializationError", "failed to encode REST request", err)
} else if value != nil { } else if value != nil {
uri := r.HTTPRequest.URL.Path uri := r.HTTPRequest.URL.Path
uri = strings.Replace(uri, "{"+name+"}", EscapePath(*value, true), -1) uri = strings.Replace(uri, "{"+name+"}", EscapePath(*value, true), -1)
@@ -144,10 +144,10 @@ func buildURI(r *aws.Request, v reflect.Value, name string) {
} }
} }
func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) { func buildQueryString(r *request.Request, v reflect.Value, name string, query url.Values) {
str, err := convertType(v) str, err := convertType(v)
if err != nil { if err != nil {
r.Error = apierr.New("Marshal", "failed to encode REST request", err) r.Error = awserr.New("SerializationError", "failed to encode REST request", err)
} else if str != nil { } else if str != nil {
query.Set(name, *str) query.Set(name, *str)
} }
@@ -156,8 +156,13 @@ func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Va
func updatePath(url *url.URL, urlPath string) { func updatePath(url *url.URL, urlPath string) {
scheme, query := url.Scheme, url.RawQuery scheme, query := url.Scheme, url.RawQuery
hasSlash := strings.HasSuffix(urlPath, "/")
// clean up path // clean up path
urlPath = path.Clean(urlPath) urlPath = path.Clean(urlPath)
if hasSlash && !strings.HasSuffix(urlPath, "/") {
urlPath += "/"
}
// get formatted URL minus scheme so we can build this into Opaque // get formatted URL minus scheme so we can build this into Opaque
url.Scheme, url.Path, url.RawQuery = "", "", "" url.Scheme, url.Path, url.RawQuery = "", "", ""

View File

@@ -11,19 +11,28 @@ import (
"time" "time"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
) )
// Unmarshal unmarshals the REST component of a response in a REST service. // Unmarshal unmarshals the REST component of a response in a REST service.
func Unmarshal(r *aws.Request) { func Unmarshal(r *request.Request) {
if r.DataFilled() { if r.DataFilled() {
v := reflect.Indirect(reflect.ValueOf(r.Data)) v := reflect.Indirect(reflect.ValueOf(r.Data))
unmarshalBody(r, v) unmarshalBody(r, v)
}
}
// UnmarshalMeta unmarshals the REST metadata of a response in a REST service
func UnmarshalMeta(r *request.Request) {
r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid")
if r.DataFilled() {
v := reflect.Indirect(reflect.ValueOf(r.Data))
unmarshalLocationElements(r, v) unmarshalLocationElements(r, v)
} }
} }
func unmarshalBody(r *aws.Request, v reflect.Value) { func unmarshalBody(r *request.Request, v reflect.Value) {
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" { if payloadName := field.Tag.Get("payload"); payloadName != "" {
pfield, _ := v.Type().FieldByName(payloadName) pfield, _ := v.Type().FieldByName(payloadName)
@@ -34,14 +43,14 @@ func unmarshalBody(r *aws.Request, v reflect.Value) {
case []byte: case []byte:
b, err := ioutil.ReadAll(r.HTTPResponse.Body) b, err := ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
} else { } else {
payload.Set(reflect.ValueOf(b)) payload.Set(reflect.ValueOf(b))
} }
case *string: case *string:
b, err := ioutil.ReadAll(r.HTTPResponse.Body) b, err := ioutil.ReadAll(r.HTTPResponse.Body)
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
} else { } else {
str := string(b) str := string(b)
payload.Set(reflect.ValueOf(&str)) payload.Set(reflect.ValueOf(&str))
@@ -53,7 +62,7 @@ func unmarshalBody(r *aws.Request, v reflect.Value) {
case "aws.ReadSeekCloser", "io.ReadCloser": case "aws.ReadSeekCloser", "io.ReadCloser":
payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) payload.Set(reflect.ValueOf(r.HTTPResponse.Body))
default: default:
r.Error = apierr.New("Unmarshal", r.Error = awserr.New("SerializationError",
"failed to decode REST response", "failed to decode REST response",
fmt.Errorf("unknown payload type %s", payload.Type())) fmt.Errorf("unknown payload type %s", payload.Type()))
} }
@@ -64,7 +73,7 @@ func unmarshalBody(r *aws.Request, v reflect.Value) {
} }
} }
func unmarshalLocationElements(r *aws.Request, v reflect.Value) { func unmarshalLocationElements(r *request.Request, v reflect.Value) {
for i := 0; i < v.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
m, field := v.Field(i), v.Type().Field(i) m, field := v.Field(i), v.Type().Field(i)
if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) {
@@ -83,14 +92,14 @@ func unmarshalLocationElements(r *aws.Request, v reflect.Value) {
case "header": case "header":
err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name))
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
break break
} }
case "headers": case "headers":
prefix := field.Tag.Get("locationName") prefix := field.Tag.Get("locationName")
err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix)
if err != nil { if err != nil {
r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
break break
} }
} }

View File

@@ -114,7 +114,7 @@ func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
for _, a := range node.Attr { for _, a := range node.Attr {
if name == a.Name.Local { if name == a.Name.Local {
// turn this into a text node for de-serializing // turn this into a text node for de-serializing
elems = []*XMLNode{&XMLNode{Text: a.Value}} elems = []*XMLNode{{Text: a.Value}}
} }
} }
} }

View File

@@ -14,10 +14,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/internal/protocol/rest"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/internal/protocol/rest"
) )
const ( const (
@@ -39,13 +39,12 @@ type signer struct {
ExpireTime time.Duration ExpireTime time.Duration
ServiceName string ServiceName string
Region string Region string
AccessKeyID string CredValues credentials.Value
SecretAccessKey string Credentials *credentials.Credentials
SessionToken string
Query url.Values Query url.Values
Body io.ReadSeeker Body io.ReadSeeker
Debug uint Debug aws.LogLevelType
Logger io.Writer Logger aws.Logger
isPresign bool isPresign bool
formattedTime string formattedTime string
@@ -65,21 +64,16 @@ type signer struct {
// Will sign the requests with the service config's Credentials object // Will sign the requests with the service config's Credentials object
// Signing is skipped if the credentials is the credentials.AnonymousCredentials // Signing is skipped if the credentials is the credentials.AnonymousCredentials
// object. // object.
func Sign(req *aws.Request) { func Sign(req *request.Request) {
// If the request does not need to be signed ignore the signing of the // If the request does not need to be signed ignore the signing of the
// request if the AnonymousCredentials object is used. // request if the AnonymousCredentials object is used.
if req.Service.Config.Credentials == credentials.AnonymousCredentials { if req.Service.Config.Credentials == credentials.AnonymousCredentials {
return return
} }
creds, err := req.Service.Config.Credentials.Get()
if err != nil {
req.Error = err
return
}
region := req.Service.SigningRegion region := req.Service.SigningRegion
if region == "" { if region == "" {
region = req.Service.Config.Region region = aws.StringValue(req.Service.Config.Region)
} }
name := req.Service.SigningName name := req.Service.SigningName
@@ -95,46 +89,79 @@ func Sign(req *aws.Request) {
Body: req.Body, Body: req.Body,
ServiceName: name, ServiceName: name,
Region: region, Region: region,
AccessKeyID: creds.AccessKeyID, Credentials: req.Service.Config.Credentials,
SecretAccessKey: creds.SecretAccessKey, Debug: req.Service.Config.LogLevel.Value(),
SessionToken: creds.SessionToken,
Debug: req.Service.Config.LogLevel,
Logger: req.Service.Config.Logger, Logger: req.Service.Config.Logger,
} }
s.sign()
return req.Error = s.sign()
} }
func (v4 *signer) sign() { func (v4 *signer) sign() error {
if v4.ExpireTime != 0 { if v4.ExpireTime != 0 {
v4.isPresign = true v4.isPresign = true
} }
if v4.isRequestSigned() {
if !v4.Credentials.IsExpired() {
// If the request is already signed, and the credentials have not
// expired yet ignore the signing request.
return nil
}
// The credentials have expired for this request. The current signing
// is invalid, and needs to be request because the request will fail.
if v4.isPresign {
v4.removePresign()
// Update the request's query string to ensure the values stays in
// sync in the case retrieving the new credentials fails.
v4.Request.URL.RawQuery = v4.Query.Encode()
}
}
var err error
v4.CredValues, err = v4.Credentials.Get()
if err != nil {
return err
}
if v4.isPresign { if v4.isPresign {
v4.Query.Set("X-Amz-Algorithm", authHeaderPrefix) v4.Query.Set("X-Amz-Algorithm", authHeaderPrefix)
if v4.SessionToken != "" { if v4.CredValues.SessionToken != "" {
v4.Query.Set("X-Amz-Security-Token", v4.SessionToken) v4.Query.Set("X-Amz-Security-Token", v4.CredValues.SessionToken)
} else { } else {
v4.Query.Del("X-Amz-Security-Token") v4.Query.Del("X-Amz-Security-Token")
} }
} else if v4.SessionToken != "" { } else if v4.CredValues.SessionToken != "" {
v4.Request.Header.Set("X-Amz-Security-Token", v4.SessionToken) v4.Request.Header.Set("X-Amz-Security-Token", v4.CredValues.SessionToken)
} }
v4.build() v4.build()
if v4.Debug > 0 { if v4.Debug.Matches(aws.LogDebugWithSigning) {
out := v4.Logger v4.logSigningInfo()
fmt.Fprintf(out, "---[ CANONICAL STRING ]-----------------------------\n") }
fmt.Fprintln(out, v4.canonicalString)
fmt.Fprintf(out, "---[ STRING TO SIGN ]--------------------------------\n") return nil
fmt.Fprintln(out, v4.stringToSign) }
const logSignInfoMsg = `DEBUG: Request Signiture:
---[ CANONICAL STRING ]-----------------------------
%s
---[ STRING TO SIGN ]--------------------------------
%s%s
-----------------------------------------------------`
const logSignedURLMsg = `
---[ SIGNED URL ]------------------------------------
%s`
func (v4 *signer) logSigningInfo() {
signedURLMsg := ""
if v4.isPresign { if v4.isPresign {
fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n") signedURLMsg = fmt.Sprintf(logSignedURLMsg, v4.Request.URL.String())
fmt.Fprintln(out, v4.Request.URL)
}
fmt.Fprintf(out, "-----------------------------------------------------\n")
} }
msg := fmt.Sprintf(logSignInfoMsg, v4.canonicalString, v4.stringToSign, signedURLMsg)
v4.Logger.Log(msg)
} }
func (v4 *signer) build() { func (v4 *signer) build() {
@@ -152,7 +179,7 @@ func (v4 *signer) build() {
v4.Request.URL.RawQuery += "&X-Amz-Signature=" + v4.signature v4.Request.URL.RawQuery += "&X-Amz-Signature=" + v4.signature
} else { } else {
parts := []string{ parts := []string{
authHeaderPrefix + " Credential=" + v4.AccessKeyID + "/" + v4.credentialString, authHeaderPrefix + " Credential=" + v4.CredValues.AccessKeyID + "/" + v4.credentialString,
"SignedHeaders=" + v4.signedHeaders, "SignedHeaders=" + v4.signedHeaders,
"Signature=" + v4.signature, "Signature=" + v4.signature,
} }
@@ -182,7 +209,7 @@ func (v4 *signer) buildCredentialString() {
}, "/") }, "/")
if v4.isPresign { if v4.isPresign {
v4.Query.Set("X-Amz-Credential", v4.AccessKeyID+"/"+v4.credentialString) v4.Query.Set("X-Amz-Credential", v4.CredValues.AccessKeyID+"/"+v4.credentialString)
} }
} }
@@ -269,7 +296,7 @@ func (v4 *signer) buildStringToSign() {
} }
func (v4 *signer) buildSignature() { func (v4 *signer) buildSignature() {
secret := v4.SecretAccessKey secret := v4.CredValues.SecretAccessKey
date := makeHmac([]byte("AWS4"+secret), []byte(v4.formattedShortTime)) date := makeHmac([]byte("AWS4"+secret), []byte(v4.formattedShortTime))
region := makeHmac(date, []byte(v4.Region)) region := makeHmac(date, []byte(v4.Region))
service := makeHmac(region, []byte(v4.ServiceName)) service := makeHmac(region, []byte(v4.ServiceName))
@@ -293,6 +320,29 @@ func (v4 *signer) bodyDigest() string {
return hash return hash
} }
// isRequestSigned returns if the request is currently signed or presigned
func (v4 *signer) isRequestSigned() bool {
if v4.isPresign && v4.Query.Get("X-Amz-Signature") != "" {
return true
}
if v4.Request.Header.Get("Authorization") != "" {
return true
}
return false
}
// unsign removes signing flags for both signed and presigned requests.
func (v4 *signer) removePresign() {
v4.Query.Del("X-Amz-Algorithm")
v4.Query.Del("X-Amz-Signature")
v4.Query.Del("X-Amz-Security-Token")
v4.Query.Del("X-Amz-Date")
v4.Query.Del("X-Amz-Expires")
v4.Query.Del("X-Amz-Credential")
v4.Query.Del("X-Amz-SignedHeaders")
}
func makeHmac(key []byte, data []byte) []byte { func makeHmac(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key) hash := hmac.New(sha256.New, key)
hash.Write(data) hash.Write(data)
@@ -306,21 +356,10 @@ func makeSha256(data []byte) []byte {
} }
func makeSha256Reader(reader io.ReadSeeker) []byte { func makeSha256Reader(reader io.ReadSeeker) []byte {
packet := make([]byte, 4096)
hash := sha256.New() hash := sha256.New()
start, _ := reader.Seek(0, 1) start, _ := reader.Seek(0, 1)
defer reader.Seek(start, 0) defer reader.Seek(start, 0)
for { io.Copy(hash, reader)
n, err := reader.Read(packet)
if n > 0 {
hash.Write(packet[0:n])
}
if err == io.EOF || n == 0 {
break
}
}
return hash.Sum(nil) return hash.Sum(nil)
} }

View File

@@ -8,6 +8,8 @@ import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@@ -29,9 +31,7 @@ func buildSigner(serviceName string, region string, signTime time.Time, expireTi
Body: reader, Body: reader,
ServiceName: serviceName, ServiceName: serviceName,
Region: region, Region: region,
AccessKeyID: "AKID", Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"),
SecretAccessKey: "SECRET",
SessionToken: "SESSION",
} }
} }
@@ -118,9 +118,9 @@ func TestSignPrecomputedBodyChecksum(t *testing.T) {
} }
func TestAnonymousCredentials(t *testing.T) { func TestAnonymousCredentials(t *testing.T) {
r := aws.NewRequest( svc := service.New(&aws.Config{Credentials: credentials.AnonymousCredentials})
aws.NewService(&aws.Config{Credentials: credentials.AnonymousCredentials}), r := svc.NewRequest(
&aws.Operation{ &request.Operation{
Name: "BatchGetItem", Name: "BatchGetItem",
HTTPMethod: "POST", HTTPMethod: "POST",
HTTPPath: "/", HTTPPath: "/",
@@ -141,6 +141,97 @@ func TestAnonymousCredentials(t *testing.T) {
assert.Empty(t, hQ.Get("X-Amz-Date")) assert.Empty(t, hQ.Get("X-Amz-Date"))
} }
func TestIgnoreResignRequestWithValidCreds(t *testing.T) {
svc := service.New(&aws.Config{
Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"),
Region: aws.String("us-west-2"),
})
r := svc.NewRequest(
&request.Operation{
Name: "BatchGetItem",
HTTPMethod: "POST",
HTTPPath: "/",
},
nil,
nil,
)
Sign(r)
sig := r.HTTPRequest.Header.Get("Authorization")
Sign(r)
assert.Equal(t, sig, r.HTTPRequest.Header.Get("Authorization"))
}
func TestIgnorePreResignRequestWithValidCreds(t *testing.T) {
svc := service.New(&aws.Config{
Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"),
Region: aws.String("us-west-2"),
})
r := svc.NewRequest(
&request.Operation{
Name: "BatchGetItem",
HTTPMethod: "POST",
HTTPPath: "/",
},
nil,
nil,
)
r.ExpireTime = time.Minute * 10
Sign(r)
sig := r.HTTPRequest.Header.Get("X-Amz-Signature")
Sign(r)
assert.Equal(t, sig, r.HTTPRequest.Header.Get("X-Amz-Signature"))
}
func TestResignRequestExpiredCreds(t *testing.T) {
creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION")
svc := service.New(&aws.Config{Credentials: creds})
r := svc.NewRequest(
&request.Operation{
Name: "BatchGetItem",
HTTPMethod: "POST",
HTTPPath: "/",
},
nil,
nil,
)
Sign(r)
querySig := r.HTTPRequest.Header.Get("Authorization")
creds.Expire()
Sign(r)
assert.NotEqual(t, querySig, r.HTTPRequest.Header.Get("Authorization"))
}
func TestPreResignRequestExpiredCreds(t *testing.T) {
provider := &credentials.StaticProvider{credentials.Value{"AKID", "SECRET", "SESSION"}}
creds := credentials.NewCredentials(provider)
svc := service.New(&aws.Config{Credentials: creds})
r := svc.NewRequest(
&request.Operation{
Name: "BatchGetItem",
HTTPMethod: "POST",
HTTPPath: "/",
},
nil,
nil,
)
r.ExpireTime = time.Minute * 10
Sign(r)
querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature")
creds.Expire()
r.Time = time.Now().Add(time.Hour * 48)
Sign(r)
assert.NotEqual(t, querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"))
}
func BenchmarkPresignRequest(b *testing.B) { func BenchmarkPresignRequest(b *testing.B) {
signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}") signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}")
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {

File diff suppressed because it is too large Load Diff

View File

@@ -4,98 +4,217 @@
package autoscalingiface package autoscalingiface
import ( import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/autoscaling"
) )
// AutoScalingAPI is the interface type for autoscaling.AutoScaling. // AutoScalingAPI is the interface type for autoscaling.AutoScaling.
type AutoScalingAPI interface { type AutoScalingAPI interface {
AttachInstancesRequest(*autoscaling.AttachInstancesInput) (*request.Request, *autoscaling.AttachInstancesOutput)
AttachInstances(*autoscaling.AttachInstancesInput) (*autoscaling.AttachInstancesOutput, error) AttachInstances(*autoscaling.AttachInstancesInput) (*autoscaling.AttachInstancesOutput, error)
AttachLoadBalancersRequest(*autoscaling.AttachLoadBalancersInput) (*request.Request, *autoscaling.AttachLoadBalancersOutput)
AttachLoadBalancers(*autoscaling.AttachLoadBalancersInput) (*autoscaling.AttachLoadBalancersOutput, error)
CompleteLifecycleActionRequest(*autoscaling.CompleteLifecycleActionInput) (*request.Request, *autoscaling.CompleteLifecycleActionOutput)
CompleteLifecycleAction(*autoscaling.CompleteLifecycleActionInput) (*autoscaling.CompleteLifecycleActionOutput, error) CompleteLifecycleAction(*autoscaling.CompleteLifecycleActionInput) (*autoscaling.CompleteLifecycleActionOutput, error)
CreateAutoScalingGroupRequest(*autoscaling.CreateAutoScalingGroupInput) (*request.Request, *autoscaling.CreateAutoScalingGroupOutput)
CreateAutoScalingGroup(*autoscaling.CreateAutoScalingGroupInput) (*autoscaling.CreateAutoScalingGroupOutput, error) CreateAutoScalingGroup(*autoscaling.CreateAutoScalingGroupInput) (*autoscaling.CreateAutoScalingGroupOutput, error)
CreateLaunchConfigurationRequest(*autoscaling.CreateLaunchConfigurationInput) (*request.Request, *autoscaling.CreateLaunchConfigurationOutput)
CreateLaunchConfiguration(*autoscaling.CreateLaunchConfigurationInput) (*autoscaling.CreateLaunchConfigurationOutput, error) CreateLaunchConfiguration(*autoscaling.CreateLaunchConfigurationInput) (*autoscaling.CreateLaunchConfigurationOutput, error)
CreateOrUpdateTagsRequest(*autoscaling.CreateOrUpdateTagsInput) (*request.Request, *autoscaling.CreateOrUpdateTagsOutput)
CreateOrUpdateTags(*autoscaling.CreateOrUpdateTagsInput) (*autoscaling.CreateOrUpdateTagsOutput, error) CreateOrUpdateTags(*autoscaling.CreateOrUpdateTagsInput) (*autoscaling.CreateOrUpdateTagsOutput, error)
DeleteAutoScalingGroupRequest(*autoscaling.DeleteAutoScalingGroupInput) (*request.Request, *autoscaling.DeleteAutoScalingGroupOutput)
DeleteAutoScalingGroup(*autoscaling.DeleteAutoScalingGroupInput) (*autoscaling.DeleteAutoScalingGroupOutput, error) DeleteAutoScalingGroup(*autoscaling.DeleteAutoScalingGroupInput) (*autoscaling.DeleteAutoScalingGroupOutput, error)
DeleteLaunchConfigurationRequest(*autoscaling.DeleteLaunchConfigurationInput) (*request.Request, *autoscaling.DeleteLaunchConfigurationOutput)
DeleteLaunchConfiguration(*autoscaling.DeleteLaunchConfigurationInput) (*autoscaling.DeleteLaunchConfigurationOutput, error) DeleteLaunchConfiguration(*autoscaling.DeleteLaunchConfigurationInput) (*autoscaling.DeleteLaunchConfigurationOutput, error)
DeleteLifecycleHookRequest(*autoscaling.DeleteLifecycleHookInput) (*request.Request, *autoscaling.DeleteLifecycleHookOutput)
DeleteLifecycleHook(*autoscaling.DeleteLifecycleHookInput) (*autoscaling.DeleteLifecycleHookOutput, error) DeleteLifecycleHook(*autoscaling.DeleteLifecycleHookInput) (*autoscaling.DeleteLifecycleHookOutput, error)
DeleteNotificationConfigurationRequest(*autoscaling.DeleteNotificationConfigurationInput) (*request.Request, *autoscaling.DeleteNotificationConfigurationOutput)
DeleteNotificationConfiguration(*autoscaling.DeleteNotificationConfigurationInput) (*autoscaling.DeleteNotificationConfigurationOutput, error) DeleteNotificationConfiguration(*autoscaling.DeleteNotificationConfigurationInput) (*autoscaling.DeleteNotificationConfigurationOutput, error)
DeletePolicyRequest(*autoscaling.DeletePolicyInput) (*request.Request, *autoscaling.DeletePolicyOutput)
DeletePolicy(*autoscaling.DeletePolicyInput) (*autoscaling.DeletePolicyOutput, error) DeletePolicy(*autoscaling.DeletePolicyInput) (*autoscaling.DeletePolicyOutput, error)
DeleteScheduledActionRequest(*autoscaling.DeleteScheduledActionInput) (*request.Request, *autoscaling.DeleteScheduledActionOutput)
DeleteScheduledAction(*autoscaling.DeleteScheduledActionInput) (*autoscaling.DeleteScheduledActionOutput, error) DeleteScheduledAction(*autoscaling.DeleteScheduledActionInput) (*autoscaling.DeleteScheduledActionOutput, error)
DeleteTagsRequest(*autoscaling.DeleteTagsInput) (*request.Request, *autoscaling.DeleteTagsOutput)
DeleteTags(*autoscaling.DeleteTagsInput) (*autoscaling.DeleteTagsOutput, error) DeleteTags(*autoscaling.DeleteTagsInput) (*autoscaling.DeleteTagsOutput, error)
DescribeAccountLimitsRequest(*autoscaling.DescribeAccountLimitsInput) (*request.Request, *autoscaling.DescribeAccountLimitsOutput)
DescribeAccountLimits(*autoscaling.DescribeAccountLimitsInput) (*autoscaling.DescribeAccountLimitsOutput, error) DescribeAccountLimits(*autoscaling.DescribeAccountLimitsInput) (*autoscaling.DescribeAccountLimitsOutput, error)
DescribeAdjustmentTypesRequest(*autoscaling.DescribeAdjustmentTypesInput) (*request.Request, *autoscaling.DescribeAdjustmentTypesOutput)
DescribeAdjustmentTypes(*autoscaling.DescribeAdjustmentTypesInput) (*autoscaling.DescribeAdjustmentTypesOutput, error) DescribeAdjustmentTypes(*autoscaling.DescribeAdjustmentTypesInput) (*autoscaling.DescribeAdjustmentTypesOutput, error)
DescribeAutoScalingGroupsRequest(*autoscaling.DescribeAutoScalingGroupsInput) (*request.Request, *autoscaling.DescribeAutoScalingGroupsOutput)
DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error) DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error)
DescribeAutoScalingGroupsPages(*autoscaling.DescribeAutoScalingGroupsInput, func(*autoscaling.DescribeAutoScalingGroupsOutput, bool) bool) error
DescribeAutoScalingInstancesRequest(*autoscaling.DescribeAutoScalingInstancesInput) (*request.Request, *autoscaling.DescribeAutoScalingInstancesOutput)
DescribeAutoScalingInstances(*autoscaling.DescribeAutoScalingInstancesInput) (*autoscaling.DescribeAutoScalingInstancesOutput, error) DescribeAutoScalingInstances(*autoscaling.DescribeAutoScalingInstancesInput) (*autoscaling.DescribeAutoScalingInstancesOutput, error)
DescribeAutoScalingInstancesPages(*autoscaling.DescribeAutoScalingInstancesInput, func(*autoscaling.DescribeAutoScalingInstancesOutput, bool) bool) error
DescribeAutoScalingNotificationTypesRequest(*autoscaling.DescribeAutoScalingNotificationTypesInput) (*request.Request, *autoscaling.DescribeAutoScalingNotificationTypesOutput)
DescribeAutoScalingNotificationTypes(*autoscaling.DescribeAutoScalingNotificationTypesInput) (*autoscaling.DescribeAutoScalingNotificationTypesOutput, error) DescribeAutoScalingNotificationTypes(*autoscaling.DescribeAutoScalingNotificationTypesInput) (*autoscaling.DescribeAutoScalingNotificationTypesOutput, error)
DescribeLaunchConfigurationsRequest(*autoscaling.DescribeLaunchConfigurationsInput) (*request.Request, *autoscaling.DescribeLaunchConfigurationsOutput)
DescribeLaunchConfigurations(*autoscaling.DescribeLaunchConfigurationsInput) (*autoscaling.DescribeLaunchConfigurationsOutput, error) DescribeLaunchConfigurations(*autoscaling.DescribeLaunchConfigurationsInput) (*autoscaling.DescribeLaunchConfigurationsOutput, error)
DescribeLaunchConfigurationsPages(*autoscaling.DescribeLaunchConfigurationsInput, func(*autoscaling.DescribeLaunchConfigurationsOutput, bool) bool) error
DescribeLifecycleHookTypesRequest(*autoscaling.DescribeLifecycleHookTypesInput) (*request.Request, *autoscaling.DescribeLifecycleHookTypesOutput)
DescribeLifecycleHookTypes(*autoscaling.DescribeLifecycleHookTypesInput) (*autoscaling.DescribeLifecycleHookTypesOutput, error) DescribeLifecycleHookTypes(*autoscaling.DescribeLifecycleHookTypesInput) (*autoscaling.DescribeLifecycleHookTypesOutput, error)
DescribeLifecycleHooksRequest(*autoscaling.DescribeLifecycleHooksInput) (*request.Request, *autoscaling.DescribeLifecycleHooksOutput)
DescribeLifecycleHooks(*autoscaling.DescribeLifecycleHooksInput) (*autoscaling.DescribeLifecycleHooksOutput, error) DescribeLifecycleHooks(*autoscaling.DescribeLifecycleHooksInput) (*autoscaling.DescribeLifecycleHooksOutput, error)
DescribeLoadBalancersRequest(*autoscaling.DescribeLoadBalancersInput) (*request.Request, *autoscaling.DescribeLoadBalancersOutput)
DescribeLoadBalancers(*autoscaling.DescribeLoadBalancersInput) (*autoscaling.DescribeLoadBalancersOutput, error)
DescribeMetricCollectionTypesRequest(*autoscaling.DescribeMetricCollectionTypesInput) (*request.Request, *autoscaling.DescribeMetricCollectionTypesOutput)
DescribeMetricCollectionTypes(*autoscaling.DescribeMetricCollectionTypesInput) (*autoscaling.DescribeMetricCollectionTypesOutput, error) DescribeMetricCollectionTypes(*autoscaling.DescribeMetricCollectionTypesInput) (*autoscaling.DescribeMetricCollectionTypesOutput, error)
DescribeNotificationConfigurationsRequest(*autoscaling.DescribeNotificationConfigurationsInput) (*request.Request, *autoscaling.DescribeNotificationConfigurationsOutput)
DescribeNotificationConfigurations(*autoscaling.DescribeNotificationConfigurationsInput) (*autoscaling.DescribeNotificationConfigurationsOutput, error) DescribeNotificationConfigurations(*autoscaling.DescribeNotificationConfigurationsInput) (*autoscaling.DescribeNotificationConfigurationsOutput, error)
DescribeNotificationConfigurationsPages(*autoscaling.DescribeNotificationConfigurationsInput, func(*autoscaling.DescribeNotificationConfigurationsOutput, bool) bool) error
DescribePoliciesRequest(*autoscaling.DescribePoliciesInput) (*request.Request, *autoscaling.DescribePoliciesOutput)
DescribePolicies(*autoscaling.DescribePoliciesInput) (*autoscaling.DescribePoliciesOutput, error) DescribePolicies(*autoscaling.DescribePoliciesInput) (*autoscaling.DescribePoliciesOutput, error)
DescribePoliciesPages(*autoscaling.DescribePoliciesInput, func(*autoscaling.DescribePoliciesOutput, bool) bool) error
DescribeScalingActivitiesRequest(*autoscaling.DescribeScalingActivitiesInput) (*request.Request, *autoscaling.DescribeScalingActivitiesOutput)
DescribeScalingActivities(*autoscaling.DescribeScalingActivitiesInput) (*autoscaling.DescribeScalingActivitiesOutput, error) DescribeScalingActivities(*autoscaling.DescribeScalingActivitiesInput) (*autoscaling.DescribeScalingActivitiesOutput, error)
DescribeScalingActivitiesPages(*autoscaling.DescribeScalingActivitiesInput, func(*autoscaling.DescribeScalingActivitiesOutput, bool) bool) error
DescribeScalingProcessTypesRequest(*autoscaling.DescribeScalingProcessTypesInput) (*request.Request, *autoscaling.DescribeScalingProcessTypesOutput)
DescribeScalingProcessTypes(*autoscaling.DescribeScalingProcessTypesInput) (*autoscaling.DescribeScalingProcessTypesOutput, error) DescribeScalingProcessTypes(*autoscaling.DescribeScalingProcessTypesInput) (*autoscaling.DescribeScalingProcessTypesOutput, error)
DescribeScheduledActionsRequest(*autoscaling.DescribeScheduledActionsInput) (*request.Request, *autoscaling.DescribeScheduledActionsOutput)
DescribeScheduledActions(*autoscaling.DescribeScheduledActionsInput) (*autoscaling.DescribeScheduledActionsOutput, error) DescribeScheduledActions(*autoscaling.DescribeScheduledActionsInput) (*autoscaling.DescribeScheduledActionsOutput, error)
DescribeScheduledActionsPages(*autoscaling.DescribeScheduledActionsInput, func(*autoscaling.DescribeScheduledActionsOutput, bool) bool) error
DescribeTagsRequest(*autoscaling.DescribeTagsInput) (*request.Request, *autoscaling.DescribeTagsOutput)
DescribeTags(*autoscaling.DescribeTagsInput) (*autoscaling.DescribeTagsOutput, error) DescribeTags(*autoscaling.DescribeTagsInput) (*autoscaling.DescribeTagsOutput, error)
DescribeTagsPages(*autoscaling.DescribeTagsInput, func(*autoscaling.DescribeTagsOutput, bool) bool) error
DescribeTerminationPolicyTypesRequest(*autoscaling.DescribeTerminationPolicyTypesInput) (*request.Request, *autoscaling.DescribeTerminationPolicyTypesOutput)
DescribeTerminationPolicyTypes(*autoscaling.DescribeTerminationPolicyTypesInput) (*autoscaling.DescribeTerminationPolicyTypesOutput, error) DescribeTerminationPolicyTypes(*autoscaling.DescribeTerminationPolicyTypesInput) (*autoscaling.DescribeTerminationPolicyTypesOutput, error)
DetachInstancesRequest(*autoscaling.DetachInstancesInput) (*request.Request, *autoscaling.DetachInstancesOutput)
DetachInstances(*autoscaling.DetachInstancesInput) (*autoscaling.DetachInstancesOutput, error) DetachInstances(*autoscaling.DetachInstancesInput) (*autoscaling.DetachInstancesOutput, error)
DetachLoadBalancersRequest(*autoscaling.DetachLoadBalancersInput) (*request.Request, *autoscaling.DetachLoadBalancersOutput)
DetachLoadBalancers(*autoscaling.DetachLoadBalancersInput) (*autoscaling.DetachLoadBalancersOutput, error)
DisableMetricsCollectionRequest(*autoscaling.DisableMetricsCollectionInput) (*request.Request, *autoscaling.DisableMetricsCollectionOutput)
DisableMetricsCollection(*autoscaling.DisableMetricsCollectionInput) (*autoscaling.DisableMetricsCollectionOutput, error) DisableMetricsCollection(*autoscaling.DisableMetricsCollectionInput) (*autoscaling.DisableMetricsCollectionOutput, error)
EnableMetricsCollectionRequest(*autoscaling.EnableMetricsCollectionInput) (*request.Request, *autoscaling.EnableMetricsCollectionOutput)
EnableMetricsCollection(*autoscaling.EnableMetricsCollectionInput) (*autoscaling.EnableMetricsCollectionOutput, error) EnableMetricsCollection(*autoscaling.EnableMetricsCollectionInput) (*autoscaling.EnableMetricsCollectionOutput, error)
EnterStandbyRequest(*autoscaling.EnterStandbyInput) (*request.Request, *autoscaling.EnterStandbyOutput)
EnterStandby(*autoscaling.EnterStandbyInput) (*autoscaling.EnterStandbyOutput, error) EnterStandby(*autoscaling.EnterStandbyInput) (*autoscaling.EnterStandbyOutput, error)
ExecutePolicyRequest(*autoscaling.ExecutePolicyInput) (*request.Request, *autoscaling.ExecutePolicyOutput)
ExecutePolicy(*autoscaling.ExecutePolicyInput) (*autoscaling.ExecutePolicyOutput, error) ExecutePolicy(*autoscaling.ExecutePolicyInput) (*autoscaling.ExecutePolicyOutput, error)
ExitStandbyRequest(*autoscaling.ExitStandbyInput) (*request.Request, *autoscaling.ExitStandbyOutput)
ExitStandby(*autoscaling.ExitStandbyInput) (*autoscaling.ExitStandbyOutput, error) ExitStandby(*autoscaling.ExitStandbyInput) (*autoscaling.ExitStandbyOutput, error)
PutLifecycleHookRequest(*autoscaling.PutLifecycleHookInput) (*request.Request, *autoscaling.PutLifecycleHookOutput)
PutLifecycleHook(*autoscaling.PutLifecycleHookInput) (*autoscaling.PutLifecycleHookOutput, error) PutLifecycleHook(*autoscaling.PutLifecycleHookInput) (*autoscaling.PutLifecycleHookOutput, error)
PutNotificationConfigurationRequest(*autoscaling.PutNotificationConfigurationInput) (*request.Request, *autoscaling.PutNotificationConfigurationOutput)
PutNotificationConfiguration(*autoscaling.PutNotificationConfigurationInput) (*autoscaling.PutNotificationConfigurationOutput, error) PutNotificationConfiguration(*autoscaling.PutNotificationConfigurationInput) (*autoscaling.PutNotificationConfigurationOutput, error)
PutScalingPolicyRequest(*autoscaling.PutScalingPolicyInput) (*request.Request, *autoscaling.PutScalingPolicyOutput)
PutScalingPolicy(*autoscaling.PutScalingPolicyInput) (*autoscaling.PutScalingPolicyOutput, error) PutScalingPolicy(*autoscaling.PutScalingPolicyInput) (*autoscaling.PutScalingPolicyOutput, error)
PutScheduledUpdateGroupActionRequest(*autoscaling.PutScheduledUpdateGroupActionInput) (*request.Request, *autoscaling.PutScheduledUpdateGroupActionOutput)
PutScheduledUpdateGroupAction(*autoscaling.PutScheduledUpdateGroupActionInput) (*autoscaling.PutScheduledUpdateGroupActionOutput, error) PutScheduledUpdateGroupAction(*autoscaling.PutScheduledUpdateGroupActionInput) (*autoscaling.PutScheduledUpdateGroupActionOutput, error)
RecordLifecycleActionHeartbeatRequest(*autoscaling.RecordLifecycleActionHeartbeatInput) (*request.Request, *autoscaling.RecordLifecycleActionHeartbeatOutput)
RecordLifecycleActionHeartbeat(*autoscaling.RecordLifecycleActionHeartbeatInput) (*autoscaling.RecordLifecycleActionHeartbeatOutput, error) RecordLifecycleActionHeartbeat(*autoscaling.RecordLifecycleActionHeartbeatInput) (*autoscaling.RecordLifecycleActionHeartbeatOutput, error)
ResumeProcessesRequest(*autoscaling.ScalingProcessQuery) (*request.Request, *autoscaling.ResumeProcessesOutput)
ResumeProcesses(*autoscaling.ScalingProcessQuery) (*autoscaling.ResumeProcessesOutput, error) ResumeProcesses(*autoscaling.ScalingProcessQuery) (*autoscaling.ResumeProcessesOutput, error)
SetDesiredCapacityRequest(*autoscaling.SetDesiredCapacityInput) (*request.Request, *autoscaling.SetDesiredCapacityOutput)
SetDesiredCapacity(*autoscaling.SetDesiredCapacityInput) (*autoscaling.SetDesiredCapacityOutput, error) SetDesiredCapacity(*autoscaling.SetDesiredCapacityInput) (*autoscaling.SetDesiredCapacityOutput, error)
SetInstanceHealthRequest(*autoscaling.SetInstanceHealthInput) (*request.Request, *autoscaling.SetInstanceHealthOutput)
SetInstanceHealth(*autoscaling.SetInstanceHealthInput) (*autoscaling.SetInstanceHealthOutput, error) SetInstanceHealth(*autoscaling.SetInstanceHealthInput) (*autoscaling.SetInstanceHealthOutput, error)
SuspendProcessesRequest(*autoscaling.ScalingProcessQuery) (*request.Request, *autoscaling.SuspendProcessesOutput)
SuspendProcesses(*autoscaling.ScalingProcessQuery) (*autoscaling.SuspendProcessesOutput, error) SuspendProcesses(*autoscaling.ScalingProcessQuery) (*autoscaling.SuspendProcessesOutput, error)
TerminateInstanceInAutoScalingGroupRequest(*autoscaling.TerminateInstanceInAutoScalingGroupInput) (*request.Request, *autoscaling.TerminateInstanceInAutoScalingGroupOutput)
TerminateInstanceInAutoScalingGroup(*autoscaling.TerminateInstanceInAutoScalingGroupInput) (*autoscaling.TerminateInstanceInAutoScalingGroupOutput, error) TerminateInstanceInAutoScalingGroup(*autoscaling.TerminateInstanceInAutoScalingGroupInput) (*autoscaling.TerminateInstanceInAutoScalingGroupOutput, error)
UpdateAutoScalingGroupRequest(*autoscaling.UpdateAutoScalingGroupInput) (*request.Request, *autoscaling.UpdateAutoScalingGroupOutput)
UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error)
} }

File diff suppressed because it is too large Load Diff

View File

@@ -4,27 +4,35 @@ package autoscaling
import ( import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/query"
"github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/signer/v4"
) )
// AutoScaling is a client for Auto Scaling. // Auto Scaling is designed to automatically launch or terminate EC2 instances
// based on user-defined policies, schedules, and health checks. Use this service
// in conjunction with the Amazon CloudWatch and Elastic Load Balancing services.
type AutoScaling struct { type AutoScaling struct {
*aws.Service *service.Service
} }
// Used for custom service initialization logic // Used for custom service initialization logic
var initService func(*aws.Service) var initService func(*service.Service)
// Used for custom request initialization logic // Used for custom request initialization logic
var initRequest func(*aws.Request) var initRequest func(*request.Request)
// New returns a new AutoScaling client. // New returns a new AutoScaling client.
func New(config *aws.Config) *AutoScaling { func New(config *aws.Config) *AutoScaling {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "autoscaling", ServiceName: "autoscaling",
APIVersion: "2011-01-01", APIVersion: "2011-01-01",
},
} }
service.Initialize() service.Initialize()
@@ -45,8 +53,8 @@ func New(config *aws.Config) *AutoScaling {
// newRequest creates a new request for a AutoScaling operation and runs any // newRequest creates a new request for a AutoScaling operation and runs any
// custom request initialization. // custom request initialization.
func (c *AutoScaling) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *AutoScaling) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
// Run custom request initialization if present // Run custom request initialization if present
if initRequest != nil { if initRequest != nil {

File diff suppressed because it is too large Load Diff

View File

@@ -3,19 +3,19 @@ package ec2
import ( import (
"time" "time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/request"
) )
func init() { func init() {
initRequest = func(r *aws.Request) { initRequest = func(r *request.Request) {
if r.Operation == opCopySnapshot { // fill the PresignedURL parameter if r.Operation.Name == opCopySnapshot { // fill the PresignedURL parameter
r.Handlers.Build.PushFront(fillPresignedURL) r.Handlers.Build.PushFront(fillPresignedURL)
} }
} }
} }
func fillPresignedURL(r *aws.Request) { func fillPresignedURL(r *request.Request) {
if !r.ParamsFilled() { if !r.ParamsFilled() {
return return
} }
@@ -23,7 +23,7 @@ func fillPresignedURL(r *aws.Request) {
params := r.Params.(*CopySnapshotInput) params := r.Params.(*CopySnapshotInput)
// Stop if PresignedURL/DestinationRegion is set // Stop if PresignedURL/DestinationRegion is set
if params.PresignedURL != nil || params.DestinationRegion != nil { if params.PresignedUrl != nil || params.DestinationRegion != nil {
return return
} }
@@ -33,16 +33,16 @@ func fillPresignedURL(r *aws.Request) {
// Set destination region. Avoids infinite handler loop. // Set destination region. Avoids infinite handler loop.
// Also needed to sign sub-request. // Also needed to sign sub-request.
params.DestinationRegion = &r.Service.Config.Region params.DestinationRegion = r.Service.Config.Region
// Create a new client pointing at source region. // Create a new client pointing at source region.
// We will use this to presign the CopySnapshot request against // We will use this to presign the CopySnapshot request against
// the source region // the source region
config := r.Service.Config.Copy() config := r.Service.Config.Copy().
WithEndpoint("").
WithRegion(*params.SourceRegion)
config.Endpoint = "" client := New(config)
config.Region = *params.SourceRegion
client := New(&config)
// Presign a CopySnapshot request with modified params // Presign a CopySnapshot request with modified params
req, _ := client.CopySnapshotRequest(params) req, _ := client.CopySnapshotRequest(params)
@@ -53,5 +53,5 @@ func fillPresignedURL(r *aws.Request) {
} }
// We have our URL, set it on params // We have our URL, set it on params
params.PresignedURL = &url params.PresignedUrl = &url
} }

View File

@@ -14,7 +14,7 @@ import (
var _ = unit.Imported var _ = unit.Imported
func TestCopySnapshotPresignedURL(t *testing.T) { func TestCopySnapshotPresignedURL(t *testing.T) {
svc := ec2.New(&aws.Config{Region: "us-west-2"}) svc := ec2.New(&aws.Config{Region: aws.String("us-west-2")})
assert.NotPanics(t, func() { assert.NotPanics(t, func() {
// Doesn't panic on nil input // Doesn't panic on nil input
@@ -24,7 +24,7 @@ func TestCopySnapshotPresignedURL(t *testing.T) {
req, _ := svc.CopySnapshotRequest(&ec2.CopySnapshotInput{ req, _ := svc.CopySnapshotRequest(&ec2.CopySnapshotInput{
SourceRegion: aws.String("us-west-1"), SourceRegion: aws.String("us-west-1"),
SourceSnapshotID: aws.String("snap-id"), SourceSnapshotId: aws.String("snap-id"),
}) })
req.Sign() req.Sign()

View File

@@ -4,366 +4,753 @@
package ec2iface package ec2iface
import ( import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2"
) )
// EC2API is the interface type for ec2.EC2. // EC2API is the interface type for ec2.EC2.
type EC2API interface { type EC2API interface {
AcceptVPCPeeringConnection(*ec2.AcceptVPCPeeringConnectionInput) (*ec2.AcceptVPCPeeringConnectionOutput, error) AcceptVpcPeeringConnectionRequest(*ec2.AcceptVpcPeeringConnectionInput) (*request.Request, *ec2.AcceptVpcPeeringConnectionOutput)
AcceptVpcPeeringConnection(*ec2.AcceptVpcPeeringConnectionInput) (*ec2.AcceptVpcPeeringConnectionOutput, error)
AllocateAddressRequest(*ec2.AllocateAddressInput) (*request.Request, *ec2.AllocateAddressOutput)
AllocateAddress(*ec2.AllocateAddressInput) (*ec2.AllocateAddressOutput, error) AllocateAddress(*ec2.AllocateAddressInput) (*ec2.AllocateAddressOutput, error)
AssignPrivateIPAddresses(*ec2.AssignPrivateIPAddressesInput) (*ec2.AssignPrivateIPAddressesOutput, error) AssignPrivateIpAddressesRequest(*ec2.AssignPrivateIpAddressesInput) (*request.Request, *ec2.AssignPrivateIpAddressesOutput)
AssignPrivateIpAddresses(*ec2.AssignPrivateIpAddressesInput) (*ec2.AssignPrivateIpAddressesOutput, error)
AssociateAddressRequest(*ec2.AssociateAddressInput) (*request.Request, *ec2.AssociateAddressOutput)
AssociateAddress(*ec2.AssociateAddressInput) (*ec2.AssociateAddressOutput, error) AssociateAddress(*ec2.AssociateAddressInput) (*ec2.AssociateAddressOutput, error)
AssociateDHCPOptions(*ec2.AssociateDHCPOptionsInput) (*ec2.AssociateDHCPOptionsOutput, error) AssociateDhcpOptionsRequest(*ec2.AssociateDhcpOptionsInput) (*request.Request, *ec2.AssociateDhcpOptionsOutput)
AssociateDhcpOptions(*ec2.AssociateDhcpOptionsInput) (*ec2.AssociateDhcpOptionsOutput, error)
AssociateRouteTableRequest(*ec2.AssociateRouteTableInput) (*request.Request, *ec2.AssociateRouteTableOutput)
AssociateRouteTable(*ec2.AssociateRouteTableInput) (*ec2.AssociateRouteTableOutput, error) AssociateRouteTable(*ec2.AssociateRouteTableInput) (*ec2.AssociateRouteTableOutput, error)
AttachClassicLinkVPC(*ec2.AttachClassicLinkVPCInput) (*ec2.AttachClassicLinkVPCOutput, error) AttachClassicLinkVpcRequest(*ec2.AttachClassicLinkVpcInput) (*request.Request, *ec2.AttachClassicLinkVpcOutput)
AttachClassicLinkVpc(*ec2.AttachClassicLinkVpcInput) (*ec2.AttachClassicLinkVpcOutput, error)
AttachInternetGatewayRequest(*ec2.AttachInternetGatewayInput) (*request.Request, *ec2.AttachInternetGatewayOutput)
AttachInternetGateway(*ec2.AttachInternetGatewayInput) (*ec2.AttachInternetGatewayOutput, error) AttachInternetGateway(*ec2.AttachInternetGatewayInput) (*ec2.AttachInternetGatewayOutput, error)
AttachNetworkInterfaceRequest(*ec2.AttachNetworkInterfaceInput) (*request.Request, *ec2.AttachNetworkInterfaceOutput)
AttachNetworkInterface(*ec2.AttachNetworkInterfaceInput) (*ec2.AttachNetworkInterfaceOutput, error) AttachNetworkInterface(*ec2.AttachNetworkInterfaceInput) (*ec2.AttachNetworkInterfaceOutput, error)
AttachVPNGateway(*ec2.AttachVPNGatewayInput) (*ec2.AttachVPNGatewayOutput, error) AttachVolumeRequest(*ec2.AttachVolumeInput) (*request.Request, *ec2.VolumeAttachment)
AttachVolume(*ec2.AttachVolumeInput) (*ec2.VolumeAttachment, error) AttachVolume(*ec2.AttachVolumeInput) (*ec2.VolumeAttachment, error)
AttachVpnGatewayRequest(*ec2.AttachVpnGatewayInput) (*request.Request, *ec2.AttachVpnGatewayOutput)
AttachVpnGateway(*ec2.AttachVpnGatewayInput) (*ec2.AttachVpnGatewayOutput, error)
AuthorizeSecurityGroupEgressRequest(*ec2.AuthorizeSecurityGroupEgressInput) (*request.Request, *ec2.AuthorizeSecurityGroupEgressOutput)
AuthorizeSecurityGroupEgress(*ec2.AuthorizeSecurityGroupEgressInput) (*ec2.AuthorizeSecurityGroupEgressOutput, error) AuthorizeSecurityGroupEgress(*ec2.AuthorizeSecurityGroupEgressInput) (*ec2.AuthorizeSecurityGroupEgressOutput, error)
AuthorizeSecurityGroupIngressRequest(*ec2.AuthorizeSecurityGroupIngressInput) (*request.Request, *ec2.AuthorizeSecurityGroupIngressOutput)
AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error)
BundleInstanceRequest(*ec2.BundleInstanceInput) (*request.Request, *ec2.BundleInstanceOutput)
BundleInstance(*ec2.BundleInstanceInput) (*ec2.BundleInstanceOutput, error) BundleInstance(*ec2.BundleInstanceInput) (*ec2.BundleInstanceOutput, error)
CancelBundleTaskRequest(*ec2.CancelBundleTaskInput) (*request.Request, *ec2.CancelBundleTaskOutput)
CancelBundleTask(*ec2.CancelBundleTaskInput) (*ec2.CancelBundleTaskOutput, error) CancelBundleTask(*ec2.CancelBundleTaskInput) (*ec2.CancelBundleTaskOutput, error)
CancelConversionTaskRequest(*ec2.CancelConversionTaskInput) (*request.Request, *ec2.CancelConversionTaskOutput)
CancelConversionTask(*ec2.CancelConversionTaskInput) (*ec2.CancelConversionTaskOutput, error) CancelConversionTask(*ec2.CancelConversionTaskInput) (*ec2.CancelConversionTaskOutput, error)
CancelExportTaskRequest(*ec2.CancelExportTaskInput) (*request.Request, *ec2.CancelExportTaskOutput)
CancelExportTask(*ec2.CancelExportTaskInput) (*ec2.CancelExportTaskOutput, error) CancelExportTask(*ec2.CancelExportTaskInput) (*ec2.CancelExportTaskOutput, error)
CancelImportTaskRequest(*ec2.CancelImportTaskInput) (*request.Request, *ec2.CancelImportTaskOutput)
CancelImportTask(*ec2.CancelImportTaskInput) (*ec2.CancelImportTaskOutput, error) CancelImportTask(*ec2.CancelImportTaskInput) (*ec2.CancelImportTaskOutput, error)
CancelReservedInstancesListingRequest(*ec2.CancelReservedInstancesListingInput) (*request.Request, *ec2.CancelReservedInstancesListingOutput)
CancelReservedInstancesListing(*ec2.CancelReservedInstancesListingInput) (*ec2.CancelReservedInstancesListingOutput, error) CancelReservedInstancesListing(*ec2.CancelReservedInstancesListingInput) (*ec2.CancelReservedInstancesListingOutput, error)
CancelSpotFleetRequestsRequest(*ec2.CancelSpotFleetRequestsInput) (*request.Request, *ec2.CancelSpotFleetRequestsOutput)
CancelSpotFleetRequests(*ec2.CancelSpotFleetRequestsInput) (*ec2.CancelSpotFleetRequestsOutput, error) CancelSpotFleetRequests(*ec2.CancelSpotFleetRequestsInput) (*ec2.CancelSpotFleetRequestsOutput, error)
CancelSpotInstanceRequestsRequest(*ec2.CancelSpotInstanceRequestsInput) (*request.Request, *ec2.CancelSpotInstanceRequestsOutput)
CancelSpotInstanceRequests(*ec2.CancelSpotInstanceRequestsInput) (*ec2.CancelSpotInstanceRequestsOutput, error) CancelSpotInstanceRequests(*ec2.CancelSpotInstanceRequestsInput) (*ec2.CancelSpotInstanceRequestsOutput, error)
ConfirmProductInstanceRequest(*ec2.ConfirmProductInstanceInput) (*request.Request, *ec2.ConfirmProductInstanceOutput)
ConfirmProductInstance(*ec2.ConfirmProductInstanceInput) (*ec2.ConfirmProductInstanceOutput, error) ConfirmProductInstance(*ec2.ConfirmProductInstanceInput) (*ec2.ConfirmProductInstanceOutput, error)
CopyImageRequest(*ec2.CopyImageInput) (*request.Request, *ec2.CopyImageOutput)
CopyImage(*ec2.CopyImageInput) (*ec2.CopyImageOutput, error) CopyImage(*ec2.CopyImageInput) (*ec2.CopyImageOutput, error)
CopySnapshotRequest(*ec2.CopySnapshotInput) (*request.Request, *ec2.CopySnapshotOutput)
CopySnapshot(*ec2.CopySnapshotInput) (*ec2.CopySnapshotOutput, error) CopySnapshot(*ec2.CopySnapshotInput) (*ec2.CopySnapshotOutput, error)
CreateCustomerGatewayRequest(*ec2.CreateCustomerGatewayInput) (*request.Request, *ec2.CreateCustomerGatewayOutput)
CreateCustomerGateway(*ec2.CreateCustomerGatewayInput) (*ec2.CreateCustomerGatewayOutput, error) CreateCustomerGateway(*ec2.CreateCustomerGatewayInput) (*ec2.CreateCustomerGatewayOutput, error)
CreateDHCPOptions(*ec2.CreateDHCPOptionsInput) (*ec2.CreateDHCPOptionsOutput, error) CreateDhcpOptionsRequest(*ec2.CreateDhcpOptionsInput) (*request.Request, *ec2.CreateDhcpOptionsOutput)
CreateDhcpOptions(*ec2.CreateDhcpOptionsInput) (*ec2.CreateDhcpOptionsOutput, error)
CreateFlowLogsRequest(*ec2.CreateFlowLogsInput) (*request.Request, *ec2.CreateFlowLogsOutput)
CreateFlowLogs(*ec2.CreateFlowLogsInput) (*ec2.CreateFlowLogsOutput, error)
CreateImageRequest(*ec2.CreateImageInput) (*request.Request, *ec2.CreateImageOutput)
CreateImage(*ec2.CreateImageInput) (*ec2.CreateImageOutput, error) CreateImage(*ec2.CreateImageInput) (*ec2.CreateImageOutput, error)
CreateInstanceExportTaskRequest(*ec2.CreateInstanceExportTaskInput) (*request.Request, *ec2.CreateInstanceExportTaskOutput)
CreateInstanceExportTask(*ec2.CreateInstanceExportTaskInput) (*ec2.CreateInstanceExportTaskOutput, error) CreateInstanceExportTask(*ec2.CreateInstanceExportTaskInput) (*ec2.CreateInstanceExportTaskOutput, error)
CreateInternetGatewayRequest(*ec2.CreateInternetGatewayInput) (*request.Request, *ec2.CreateInternetGatewayOutput)
CreateInternetGateway(*ec2.CreateInternetGatewayInput) (*ec2.CreateInternetGatewayOutput, error) CreateInternetGateway(*ec2.CreateInternetGatewayInput) (*ec2.CreateInternetGatewayOutput, error)
CreateKeyPairRequest(*ec2.CreateKeyPairInput) (*request.Request, *ec2.CreateKeyPairOutput)
CreateKeyPair(*ec2.CreateKeyPairInput) (*ec2.CreateKeyPairOutput, error) CreateKeyPair(*ec2.CreateKeyPairInput) (*ec2.CreateKeyPairOutput, error)
CreateNetworkACL(*ec2.CreateNetworkACLInput) (*ec2.CreateNetworkACLOutput, error) CreateNetworkAclRequest(*ec2.CreateNetworkAclInput) (*request.Request, *ec2.CreateNetworkAclOutput)
CreateNetworkACLEntry(*ec2.CreateNetworkACLEntryInput) (*ec2.CreateNetworkACLEntryOutput, error) CreateNetworkAcl(*ec2.CreateNetworkAclInput) (*ec2.CreateNetworkAclOutput, error)
CreateNetworkAclEntryRequest(*ec2.CreateNetworkAclEntryInput) (*request.Request, *ec2.CreateNetworkAclEntryOutput)
CreateNetworkAclEntry(*ec2.CreateNetworkAclEntryInput) (*ec2.CreateNetworkAclEntryOutput, error)
CreateNetworkInterfaceRequest(*ec2.CreateNetworkInterfaceInput) (*request.Request, *ec2.CreateNetworkInterfaceOutput)
CreateNetworkInterface(*ec2.CreateNetworkInterfaceInput) (*ec2.CreateNetworkInterfaceOutput, error) CreateNetworkInterface(*ec2.CreateNetworkInterfaceInput) (*ec2.CreateNetworkInterfaceOutput, error)
CreatePlacementGroupRequest(*ec2.CreatePlacementGroupInput) (*request.Request, *ec2.CreatePlacementGroupOutput)
CreatePlacementGroup(*ec2.CreatePlacementGroupInput) (*ec2.CreatePlacementGroupOutput, error) CreatePlacementGroup(*ec2.CreatePlacementGroupInput) (*ec2.CreatePlacementGroupOutput, error)
CreateReservedInstancesListingRequest(*ec2.CreateReservedInstancesListingInput) (*request.Request, *ec2.CreateReservedInstancesListingOutput)
CreateReservedInstancesListing(*ec2.CreateReservedInstancesListingInput) (*ec2.CreateReservedInstancesListingOutput, error) CreateReservedInstancesListing(*ec2.CreateReservedInstancesListingInput) (*ec2.CreateReservedInstancesListingOutput, error)
CreateRouteRequest(*ec2.CreateRouteInput) (*request.Request, *ec2.CreateRouteOutput)
CreateRoute(*ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) CreateRoute(*ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error)
CreateRouteTableRequest(*ec2.CreateRouteTableInput) (*request.Request, *ec2.CreateRouteTableOutput)
CreateRouteTable(*ec2.CreateRouteTableInput) (*ec2.CreateRouteTableOutput, error) CreateRouteTable(*ec2.CreateRouteTableInput) (*ec2.CreateRouteTableOutput, error)
CreateSecurityGroupRequest(*ec2.CreateSecurityGroupInput) (*request.Request, *ec2.CreateSecurityGroupOutput)
CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error)
CreateSnapshotRequest(*ec2.CreateSnapshotInput) (*request.Request, *ec2.Snapshot)
CreateSnapshot(*ec2.CreateSnapshotInput) (*ec2.Snapshot, error) CreateSnapshot(*ec2.CreateSnapshotInput) (*ec2.Snapshot, error)
CreateSpotDatafeedSubscriptionRequest(*ec2.CreateSpotDatafeedSubscriptionInput) (*request.Request, *ec2.CreateSpotDatafeedSubscriptionOutput)
CreateSpotDatafeedSubscription(*ec2.CreateSpotDatafeedSubscriptionInput) (*ec2.CreateSpotDatafeedSubscriptionOutput, error) CreateSpotDatafeedSubscription(*ec2.CreateSpotDatafeedSubscriptionInput) (*ec2.CreateSpotDatafeedSubscriptionOutput, error)
CreateSubnetRequest(*ec2.CreateSubnetInput) (*request.Request, *ec2.CreateSubnetOutput)
CreateSubnet(*ec2.CreateSubnetInput) (*ec2.CreateSubnetOutput, error) CreateSubnet(*ec2.CreateSubnetInput) (*ec2.CreateSubnetOutput, error)
CreateTagsRequest(*ec2.CreateTagsInput) (*request.Request, *ec2.CreateTagsOutput)
CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error)
CreateVPC(*ec2.CreateVPCInput) (*ec2.CreateVPCOutput, error) CreateVolumeRequest(*ec2.CreateVolumeInput) (*request.Request, *ec2.Volume)
CreateVPCEndpoint(*ec2.CreateVPCEndpointInput) (*ec2.CreateVPCEndpointOutput, error)
CreateVPCPeeringConnection(*ec2.CreateVPCPeeringConnectionInput) (*ec2.CreateVPCPeeringConnectionOutput, error)
CreateVPNConnection(*ec2.CreateVPNConnectionInput) (*ec2.CreateVPNConnectionOutput, error)
CreateVPNConnectionRoute(*ec2.CreateVPNConnectionRouteInput) (*ec2.CreateVPNConnectionRouteOutput, error)
CreateVPNGateway(*ec2.CreateVPNGatewayInput) (*ec2.CreateVPNGatewayOutput, error)
CreateVolume(*ec2.CreateVolumeInput) (*ec2.Volume, error) CreateVolume(*ec2.CreateVolumeInput) (*ec2.Volume, error)
CreateVpcRequest(*ec2.CreateVpcInput) (*request.Request, *ec2.CreateVpcOutput)
CreateVpc(*ec2.CreateVpcInput) (*ec2.CreateVpcOutput, error)
CreateVpcEndpointRequest(*ec2.CreateVpcEndpointInput) (*request.Request, *ec2.CreateVpcEndpointOutput)
CreateVpcEndpoint(*ec2.CreateVpcEndpointInput) (*ec2.CreateVpcEndpointOutput, error)
CreateVpcPeeringConnectionRequest(*ec2.CreateVpcPeeringConnectionInput) (*request.Request, *ec2.CreateVpcPeeringConnectionOutput)
CreateVpcPeeringConnection(*ec2.CreateVpcPeeringConnectionInput) (*ec2.CreateVpcPeeringConnectionOutput, error)
CreateVpnConnectionRequest(*ec2.CreateVpnConnectionInput) (*request.Request, *ec2.CreateVpnConnectionOutput)
CreateVpnConnection(*ec2.CreateVpnConnectionInput) (*ec2.CreateVpnConnectionOutput, error)
CreateVpnConnectionRouteRequest(*ec2.CreateVpnConnectionRouteInput) (*request.Request, *ec2.CreateVpnConnectionRouteOutput)
CreateVpnConnectionRoute(*ec2.CreateVpnConnectionRouteInput) (*ec2.CreateVpnConnectionRouteOutput, error)
CreateVpnGatewayRequest(*ec2.CreateVpnGatewayInput) (*request.Request, *ec2.CreateVpnGatewayOutput)
CreateVpnGateway(*ec2.CreateVpnGatewayInput) (*ec2.CreateVpnGatewayOutput, error)
DeleteCustomerGatewayRequest(*ec2.DeleteCustomerGatewayInput) (*request.Request, *ec2.DeleteCustomerGatewayOutput)
DeleteCustomerGateway(*ec2.DeleteCustomerGatewayInput) (*ec2.DeleteCustomerGatewayOutput, error) DeleteCustomerGateway(*ec2.DeleteCustomerGatewayInput) (*ec2.DeleteCustomerGatewayOutput, error)
DeleteDHCPOptions(*ec2.DeleteDHCPOptionsInput) (*ec2.DeleteDHCPOptionsOutput, error) DeleteDhcpOptionsRequest(*ec2.DeleteDhcpOptionsInput) (*request.Request, *ec2.DeleteDhcpOptionsOutput)
DeleteDhcpOptions(*ec2.DeleteDhcpOptionsInput) (*ec2.DeleteDhcpOptionsOutput, error)
DeleteFlowLogsRequest(*ec2.DeleteFlowLogsInput) (*request.Request, *ec2.DeleteFlowLogsOutput)
DeleteFlowLogs(*ec2.DeleteFlowLogsInput) (*ec2.DeleteFlowLogsOutput, error)
DeleteInternetGatewayRequest(*ec2.DeleteInternetGatewayInput) (*request.Request, *ec2.DeleteInternetGatewayOutput)
DeleteInternetGateway(*ec2.DeleteInternetGatewayInput) (*ec2.DeleteInternetGatewayOutput, error) DeleteInternetGateway(*ec2.DeleteInternetGatewayInput) (*ec2.DeleteInternetGatewayOutput, error)
DeleteKeyPairRequest(*ec2.DeleteKeyPairInput) (*request.Request, *ec2.DeleteKeyPairOutput)
DeleteKeyPair(*ec2.DeleteKeyPairInput) (*ec2.DeleteKeyPairOutput, error) DeleteKeyPair(*ec2.DeleteKeyPairInput) (*ec2.DeleteKeyPairOutput, error)
DeleteNetworkACL(*ec2.DeleteNetworkACLInput) (*ec2.DeleteNetworkACLOutput, error) DeleteNetworkAclRequest(*ec2.DeleteNetworkAclInput) (*request.Request, *ec2.DeleteNetworkAclOutput)
DeleteNetworkACLEntry(*ec2.DeleteNetworkACLEntryInput) (*ec2.DeleteNetworkACLEntryOutput, error) DeleteNetworkAcl(*ec2.DeleteNetworkAclInput) (*ec2.DeleteNetworkAclOutput, error)
DeleteNetworkAclEntryRequest(*ec2.DeleteNetworkAclEntryInput) (*request.Request, *ec2.DeleteNetworkAclEntryOutput)
DeleteNetworkAclEntry(*ec2.DeleteNetworkAclEntryInput) (*ec2.DeleteNetworkAclEntryOutput, error)
DeleteNetworkInterfaceRequest(*ec2.DeleteNetworkInterfaceInput) (*request.Request, *ec2.DeleteNetworkInterfaceOutput)
DeleteNetworkInterface(*ec2.DeleteNetworkInterfaceInput) (*ec2.DeleteNetworkInterfaceOutput, error) DeleteNetworkInterface(*ec2.DeleteNetworkInterfaceInput) (*ec2.DeleteNetworkInterfaceOutput, error)
DeletePlacementGroupRequest(*ec2.DeletePlacementGroupInput) (*request.Request, *ec2.DeletePlacementGroupOutput)
DeletePlacementGroup(*ec2.DeletePlacementGroupInput) (*ec2.DeletePlacementGroupOutput, error) DeletePlacementGroup(*ec2.DeletePlacementGroupInput) (*ec2.DeletePlacementGroupOutput, error)
DeleteRouteRequest(*ec2.DeleteRouteInput) (*request.Request, *ec2.DeleteRouteOutput)
DeleteRoute(*ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) DeleteRoute(*ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error)
DeleteRouteTableRequest(*ec2.DeleteRouteTableInput) (*request.Request, *ec2.DeleteRouteTableOutput)
DeleteRouteTable(*ec2.DeleteRouteTableInput) (*ec2.DeleteRouteTableOutput, error) DeleteRouteTable(*ec2.DeleteRouteTableInput) (*ec2.DeleteRouteTableOutput, error)
DeleteSecurityGroupRequest(*ec2.DeleteSecurityGroupInput) (*request.Request, *ec2.DeleteSecurityGroupOutput)
DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error)
DeleteSnapshotRequest(*ec2.DeleteSnapshotInput) (*request.Request, *ec2.DeleteSnapshotOutput)
DeleteSnapshot(*ec2.DeleteSnapshotInput) (*ec2.DeleteSnapshotOutput, error) DeleteSnapshot(*ec2.DeleteSnapshotInput) (*ec2.DeleteSnapshotOutput, error)
DeleteSpotDatafeedSubscriptionRequest(*ec2.DeleteSpotDatafeedSubscriptionInput) (*request.Request, *ec2.DeleteSpotDatafeedSubscriptionOutput)
DeleteSpotDatafeedSubscription(*ec2.DeleteSpotDatafeedSubscriptionInput) (*ec2.DeleteSpotDatafeedSubscriptionOutput, error) DeleteSpotDatafeedSubscription(*ec2.DeleteSpotDatafeedSubscriptionInput) (*ec2.DeleteSpotDatafeedSubscriptionOutput, error)
DeleteSubnetRequest(*ec2.DeleteSubnetInput) (*request.Request, *ec2.DeleteSubnetOutput)
DeleteSubnet(*ec2.DeleteSubnetInput) (*ec2.DeleteSubnetOutput, error) DeleteSubnet(*ec2.DeleteSubnetInput) (*ec2.DeleteSubnetOutput, error)
DeleteTagsRequest(*ec2.DeleteTagsInput) (*request.Request, *ec2.DeleteTagsOutput)
DeleteTags(*ec2.DeleteTagsInput) (*ec2.DeleteTagsOutput, error) DeleteTags(*ec2.DeleteTagsInput) (*ec2.DeleteTagsOutput, error)
DeleteVPC(*ec2.DeleteVPCInput) (*ec2.DeleteVPCOutput, error) DeleteVolumeRequest(*ec2.DeleteVolumeInput) (*request.Request, *ec2.DeleteVolumeOutput)
DeleteVPCEndpoints(*ec2.DeleteVPCEndpointsInput) (*ec2.DeleteVPCEndpointsOutput, error)
DeleteVPCPeeringConnection(*ec2.DeleteVPCPeeringConnectionInput) (*ec2.DeleteVPCPeeringConnectionOutput, error)
DeleteVPNConnection(*ec2.DeleteVPNConnectionInput) (*ec2.DeleteVPNConnectionOutput, error)
DeleteVPNConnectionRoute(*ec2.DeleteVPNConnectionRouteInput) (*ec2.DeleteVPNConnectionRouteOutput, error)
DeleteVPNGateway(*ec2.DeleteVPNGatewayInput) (*ec2.DeleteVPNGatewayOutput, error)
DeleteVolume(*ec2.DeleteVolumeInput) (*ec2.DeleteVolumeOutput, error) DeleteVolume(*ec2.DeleteVolumeInput) (*ec2.DeleteVolumeOutput, error)
DeleteVpcRequest(*ec2.DeleteVpcInput) (*request.Request, *ec2.DeleteVpcOutput)
DeleteVpc(*ec2.DeleteVpcInput) (*ec2.DeleteVpcOutput, error)
DeleteVpcEndpointsRequest(*ec2.DeleteVpcEndpointsInput) (*request.Request, *ec2.DeleteVpcEndpointsOutput)
DeleteVpcEndpoints(*ec2.DeleteVpcEndpointsInput) (*ec2.DeleteVpcEndpointsOutput, error)
DeleteVpcPeeringConnectionRequest(*ec2.DeleteVpcPeeringConnectionInput) (*request.Request, *ec2.DeleteVpcPeeringConnectionOutput)
DeleteVpcPeeringConnection(*ec2.DeleteVpcPeeringConnectionInput) (*ec2.DeleteVpcPeeringConnectionOutput, error)
DeleteVpnConnectionRequest(*ec2.DeleteVpnConnectionInput) (*request.Request, *ec2.DeleteVpnConnectionOutput)
DeleteVpnConnection(*ec2.DeleteVpnConnectionInput) (*ec2.DeleteVpnConnectionOutput, error)
DeleteVpnConnectionRouteRequest(*ec2.DeleteVpnConnectionRouteInput) (*request.Request, *ec2.DeleteVpnConnectionRouteOutput)
DeleteVpnConnectionRoute(*ec2.DeleteVpnConnectionRouteInput) (*ec2.DeleteVpnConnectionRouteOutput, error)
DeleteVpnGatewayRequest(*ec2.DeleteVpnGatewayInput) (*request.Request, *ec2.DeleteVpnGatewayOutput)
DeleteVpnGateway(*ec2.DeleteVpnGatewayInput) (*ec2.DeleteVpnGatewayOutput, error)
DeregisterImageRequest(*ec2.DeregisterImageInput) (*request.Request, *ec2.DeregisterImageOutput)
DeregisterImage(*ec2.DeregisterImageInput) (*ec2.DeregisterImageOutput, error) DeregisterImage(*ec2.DeregisterImageInput) (*ec2.DeregisterImageOutput, error)
DescribeAccountAttributesRequest(*ec2.DescribeAccountAttributesInput) (*request.Request, *ec2.DescribeAccountAttributesOutput)
DescribeAccountAttributes(*ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) DescribeAccountAttributes(*ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error)
DescribeAddressesRequest(*ec2.DescribeAddressesInput) (*request.Request, *ec2.DescribeAddressesOutput)
DescribeAddresses(*ec2.DescribeAddressesInput) (*ec2.DescribeAddressesOutput, error) DescribeAddresses(*ec2.DescribeAddressesInput) (*ec2.DescribeAddressesOutput, error)
DescribeAvailabilityZonesRequest(*ec2.DescribeAvailabilityZonesInput) (*request.Request, *ec2.DescribeAvailabilityZonesOutput)
DescribeAvailabilityZones(*ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error) DescribeAvailabilityZones(*ec2.DescribeAvailabilityZonesInput) (*ec2.DescribeAvailabilityZonesOutput, error)
DescribeBundleTasksRequest(*ec2.DescribeBundleTasksInput) (*request.Request, *ec2.DescribeBundleTasksOutput)
DescribeBundleTasks(*ec2.DescribeBundleTasksInput) (*ec2.DescribeBundleTasksOutput, error) DescribeBundleTasks(*ec2.DescribeBundleTasksInput) (*ec2.DescribeBundleTasksOutput, error)
DescribeClassicLinkInstancesRequest(*ec2.DescribeClassicLinkInstancesInput) (*request.Request, *ec2.DescribeClassicLinkInstancesOutput)
DescribeClassicLinkInstances(*ec2.DescribeClassicLinkInstancesInput) (*ec2.DescribeClassicLinkInstancesOutput, error) DescribeClassicLinkInstances(*ec2.DescribeClassicLinkInstancesInput) (*ec2.DescribeClassicLinkInstancesOutput, error)
DescribeConversionTasksRequest(*ec2.DescribeConversionTasksInput) (*request.Request, *ec2.DescribeConversionTasksOutput)
DescribeConversionTasks(*ec2.DescribeConversionTasksInput) (*ec2.DescribeConversionTasksOutput, error) DescribeConversionTasks(*ec2.DescribeConversionTasksInput) (*ec2.DescribeConversionTasksOutput, error)
DescribeCustomerGatewaysRequest(*ec2.DescribeCustomerGatewaysInput) (*request.Request, *ec2.DescribeCustomerGatewaysOutput)
DescribeCustomerGateways(*ec2.DescribeCustomerGatewaysInput) (*ec2.DescribeCustomerGatewaysOutput, error) DescribeCustomerGateways(*ec2.DescribeCustomerGatewaysInput) (*ec2.DescribeCustomerGatewaysOutput, error)
DescribeDHCPOptions(*ec2.DescribeDHCPOptionsInput) (*ec2.DescribeDHCPOptionsOutput, error) DescribeDhcpOptionsRequest(*ec2.DescribeDhcpOptionsInput) (*request.Request, *ec2.DescribeDhcpOptionsOutput)
DescribeDhcpOptions(*ec2.DescribeDhcpOptionsInput) (*ec2.DescribeDhcpOptionsOutput, error)
DescribeExportTasksRequest(*ec2.DescribeExportTasksInput) (*request.Request, *ec2.DescribeExportTasksOutput)
DescribeExportTasks(*ec2.DescribeExportTasksInput) (*ec2.DescribeExportTasksOutput, error) DescribeExportTasks(*ec2.DescribeExportTasksInput) (*ec2.DescribeExportTasksOutput, error)
DescribeFlowLogsRequest(*ec2.DescribeFlowLogsInput) (*request.Request, *ec2.DescribeFlowLogsOutput)
DescribeFlowLogs(*ec2.DescribeFlowLogsInput) (*ec2.DescribeFlowLogsOutput, error)
DescribeImageAttributeRequest(*ec2.DescribeImageAttributeInput) (*request.Request, *ec2.DescribeImageAttributeOutput)
DescribeImageAttribute(*ec2.DescribeImageAttributeInput) (*ec2.DescribeImageAttributeOutput, error) DescribeImageAttribute(*ec2.DescribeImageAttributeInput) (*ec2.DescribeImageAttributeOutput, error)
DescribeImagesRequest(*ec2.DescribeImagesInput) (*request.Request, *ec2.DescribeImagesOutput)
DescribeImages(*ec2.DescribeImagesInput) (*ec2.DescribeImagesOutput, error) DescribeImages(*ec2.DescribeImagesInput) (*ec2.DescribeImagesOutput, error)
DescribeImportImageTasksRequest(*ec2.DescribeImportImageTasksInput) (*request.Request, *ec2.DescribeImportImageTasksOutput)
DescribeImportImageTasks(*ec2.DescribeImportImageTasksInput) (*ec2.DescribeImportImageTasksOutput, error) DescribeImportImageTasks(*ec2.DescribeImportImageTasksInput) (*ec2.DescribeImportImageTasksOutput, error)
DescribeImportSnapshotTasksRequest(*ec2.DescribeImportSnapshotTasksInput) (*request.Request, *ec2.DescribeImportSnapshotTasksOutput)
DescribeImportSnapshotTasks(*ec2.DescribeImportSnapshotTasksInput) (*ec2.DescribeImportSnapshotTasksOutput, error) DescribeImportSnapshotTasks(*ec2.DescribeImportSnapshotTasksInput) (*ec2.DescribeImportSnapshotTasksOutput, error)
DescribeInstanceAttributeRequest(*ec2.DescribeInstanceAttributeInput) (*request.Request, *ec2.DescribeInstanceAttributeOutput)
DescribeInstanceAttribute(*ec2.DescribeInstanceAttributeInput) (*ec2.DescribeInstanceAttributeOutput, error) DescribeInstanceAttribute(*ec2.DescribeInstanceAttributeInput) (*ec2.DescribeInstanceAttributeOutput, error)
DescribeInstanceStatusRequest(*ec2.DescribeInstanceStatusInput) (*request.Request, *ec2.DescribeInstanceStatusOutput)
DescribeInstanceStatus(*ec2.DescribeInstanceStatusInput) (*ec2.DescribeInstanceStatusOutput, error) DescribeInstanceStatus(*ec2.DescribeInstanceStatusInput) (*ec2.DescribeInstanceStatusOutput, error)
DescribeInstanceStatusPages(*ec2.DescribeInstanceStatusInput, func(*ec2.DescribeInstanceStatusOutput, bool) bool) error
DescribeInstancesRequest(*ec2.DescribeInstancesInput) (*request.Request, *ec2.DescribeInstancesOutput)
DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
DescribeInstancesPages(*ec2.DescribeInstancesInput, func(*ec2.DescribeInstancesOutput, bool) bool) error
DescribeInternetGatewaysRequest(*ec2.DescribeInternetGatewaysInput) (*request.Request, *ec2.DescribeInternetGatewaysOutput)
DescribeInternetGateways(*ec2.DescribeInternetGatewaysInput) (*ec2.DescribeInternetGatewaysOutput, error) DescribeInternetGateways(*ec2.DescribeInternetGatewaysInput) (*ec2.DescribeInternetGatewaysOutput, error)
DescribeKeyPairsRequest(*ec2.DescribeKeyPairsInput) (*request.Request, *ec2.DescribeKeyPairsOutput)
DescribeKeyPairs(*ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error) DescribeKeyPairs(*ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error)
DescribeMovingAddressesRequest(*ec2.DescribeMovingAddressesInput) (*request.Request, *ec2.DescribeMovingAddressesOutput)
DescribeMovingAddresses(*ec2.DescribeMovingAddressesInput) (*ec2.DescribeMovingAddressesOutput, error) DescribeMovingAddresses(*ec2.DescribeMovingAddressesInput) (*ec2.DescribeMovingAddressesOutput, error)
DescribeNetworkACLs(*ec2.DescribeNetworkACLsInput) (*ec2.DescribeNetworkACLsOutput, error) DescribeNetworkAclsRequest(*ec2.DescribeNetworkAclsInput) (*request.Request, *ec2.DescribeNetworkAclsOutput)
DescribeNetworkAcls(*ec2.DescribeNetworkAclsInput) (*ec2.DescribeNetworkAclsOutput, error)
DescribeNetworkInterfaceAttributeRequest(*ec2.DescribeNetworkInterfaceAttributeInput) (*request.Request, *ec2.DescribeNetworkInterfaceAttributeOutput)
DescribeNetworkInterfaceAttribute(*ec2.DescribeNetworkInterfaceAttributeInput) (*ec2.DescribeNetworkInterfaceAttributeOutput, error) DescribeNetworkInterfaceAttribute(*ec2.DescribeNetworkInterfaceAttributeInput) (*ec2.DescribeNetworkInterfaceAttributeOutput, error)
DescribeNetworkInterfacesRequest(*ec2.DescribeNetworkInterfacesInput) (*request.Request, *ec2.DescribeNetworkInterfacesOutput)
DescribeNetworkInterfaces(*ec2.DescribeNetworkInterfacesInput) (*ec2.DescribeNetworkInterfacesOutput, error) DescribeNetworkInterfaces(*ec2.DescribeNetworkInterfacesInput) (*ec2.DescribeNetworkInterfacesOutput, error)
DescribePlacementGroupsRequest(*ec2.DescribePlacementGroupsInput) (*request.Request, *ec2.DescribePlacementGroupsOutput)
DescribePlacementGroups(*ec2.DescribePlacementGroupsInput) (*ec2.DescribePlacementGroupsOutput, error) DescribePlacementGroups(*ec2.DescribePlacementGroupsInput) (*ec2.DescribePlacementGroupsOutput, error)
DescribePrefixListsRequest(*ec2.DescribePrefixListsInput) (*request.Request, *ec2.DescribePrefixListsOutput)
DescribePrefixLists(*ec2.DescribePrefixListsInput) (*ec2.DescribePrefixListsOutput, error) DescribePrefixLists(*ec2.DescribePrefixListsInput) (*ec2.DescribePrefixListsOutput, error)
DescribeRegionsRequest(*ec2.DescribeRegionsInput) (*request.Request, *ec2.DescribeRegionsOutput)
DescribeRegions(*ec2.DescribeRegionsInput) (*ec2.DescribeRegionsOutput, error) DescribeRegions(*ec2.DescribeRegionsInput) (*ec2.DescribeRegionsOutput, error)
DescribeReservedInstancesRequest(*ec2.DescribeReservedInstancesInput) (*request.Request, *ec2.DescribeReservedInstancesOutput)
DescribeReservedInstances(*ec2.DescribeReservedInstancesInput) (*ec2.DescribeReservedInstancesOutput, error) DescribeReservedInstances(*ec2.DescribeReservedInstancesInput) (*ec2.DescribeReservedInstancesOutput, error)
DescribeReservedInstancesListingsRequest(*ec2.DescribeReservedInstancesListingsInput) (*request.Request, *ec2.DescribeReservedInstancesListingsOutput)
DescribeReservedInstancesListings(*ec2.DescribeReservedInstancesListingsInput) (*ec2.DescribeReservedInstancesListingsOutput, error) DescribeReservedInstancesListings(*ec2.DescribeReservedInstancesListingsInput) (*ec2.DescribeReservedInstancesListingsOutput, error)
DescribeReservedInstancesModificationsRequest(*ec2.DescribeReservedInstancesModificationsInput) (*request.Request, *ec2.DescribeReservedInstancesModificationsOutput)
DescribeReservedInstancesModifications(*ec2.DescribeReservedInstancesModificationsInput) (*ec2.DescribeReservedInstancesModificationsOutput, error) DescribeReservedInstancesModifications(*ec2.DescribeReservedInstancesModificationsInput) (*ec2.DescribeReservedInstancesModificationsOutput, error)
DescribeReservedInstancesModificationsPages(*ec2.DescribeReservedInstancesModificationsInput, func(*ec2.DescribeReservedInstancesModificationsOutput, bool) bool) error
DescribeReservedInstancesOfferingsRequest(*ec2.DescribeReservedInstancesOfferingsInput) (*request.Request, *ec2.DescribeReservedInstancesOfferingsOutput)
DescribeReservedInstancesOfferings(*ec2.DescribeReservedInstancesOfferingsInput) (*ec2.DescribeReservedInstancesOfferingsOutput, error) DescribeReservedInstancesOfferings(*ec2.DescribeReservedInstancesOfferingsInput) (*ec2.DescribeReservedInstancesOfferingsOutput, error)
DescribeReservedInstancesOfferingsPages(*ec2.DescribeReservedInstancesOfferingsInput, func(*ec2.DescribeReservedInstancesOfferingsOutput, bool) bool) error
DescribeRouteTablesRequest(*ec2.DescribeRouteTablesInput) (*request.Request, *ec2.DescribeRouteTablesOutput)
DescribeRouteTables(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error) DescribeRouteTables(*ec2.DescribeRouteTablesInput) (*ec2.DescribeRouteTablesOutput, error)
DescribeSecurityGroupsRequest(*ec2.DescribeSecurityGroupsInput) (*request.Request, *ec2.DescribeSecurityGroupsOutput)
DescribeSecurityGroups(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) DescribeSecurityGroups(*ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error)
DescribeSnapshotAttributeRequest(*ec2.DescribeSnapshotAttributeInput) (*request.Request, *ec2.DescribeSnapshotAttributeOutput)
DescribeSnapshotAttribute(*ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error) DescribeSnapshotAttribute(*ec2.DescribeSnapshotAttributeInput) (*ec2.DescribeSnapshotAttributeOutput, error)
DescribeSnapshotsRequest(*ec2.DescribeSnapshotsInput) (*request.Request, *ec2.DescribeSnapshotsOutput)
DescribeSnapshots(*ec2.DescribeSnapshotsInput) (*ec2.DescribeSnapshotsOutput, error) DescribeSnapshots(*ec2.DescribeSnapshotsInput) (*ec2.DescribeSnapshotsOutput, error)
DescribeSnapshotsPages(*ec2.DescribeSnapshotsInput, func(*ec2.DescribeSnapshotsOutput, bool) bool) error
DescribeSpotDatafeedSubscriptionRequest(*ec2.DescribeSpotDatafeedSubscriptionInput) (*request.Request, *ec2.DescribeSpotDatafeedSubscriptionOutput)
DescribeSpotDatafeedSubscription(*ec2.DescribeSpotDatafeedSubscriptionInput) (*ec2.DescribeSpotDatafeedSubscriptionOutput, error) DescribeSpotDatafeedSubscription(*ec2.DescribeSpotDatafeedSubscriptionInput) (*ec2.DescribeSpotDatafeedSubscriptionOutput, error)
DescribeSpotFleetInstancesRequest(*ec2.DescribeSpotFleetInstancesInput) (*request.Request, *ec2.DescribeSpotFleetInstancesOutput)
DescribeSpotFleetInstances(*ec2.DescribeSpotFleetInstancesInput) (*ec2.DescribeSpotFleetInstancesOutput, error) DescribeSpotFleetInstances(*ec2.DescribeSpotFleetInstancesInput) (*ec2.DescribeSpotFleetInstancesOutput, error)
DescribeSpotFleetRequestHistoryRequest(*ec2.DescribeSpotFleetRequestHistoryInput) (*request.Request, *ec2.DescribeSpotFleetRequestHistoryOutput)
DescribeSpotFleetRequestHistory(*ec2.DescribeSpotFleetRequestHistoryInput) (*ec2.DescribeSpotFleetRequestHistoryOutput, error) DescribeSpotFleetRequestHistory(*ec2.DescribeSpotFleetRequestHistoryInput) (*ec2.DescribeSpotFleetRequestHistoryOutput, error)
DescribeSpotFleetRequestsRequest(*ec2.DescribeSpotFleetRequestsInput) (*request.Request, *ec2.DescribeSpotFleetRequestsOutput)
DescribeSpotFleetRequests(*ec2.DescribeSpotFleetRequestsInput) (*ec2.DescribeSpotFleetRequestsOutput, error) DescribeSpotFleetRequests(*ec2.DescribeSpotFleetRequestsInput) (*ec2.DescribeSpotFleetRequestsOutput, error)
DescribeSpotInstanceRequestsRequest(*ec2.DescribeSpotInstanceRequestsInput) (*request.Request, *ec2.DescribeSpotInstanceRequestsOutput)
DescribeSpotInstanceRequests(*ec2.DescribeSpotInstanceRequestsInput) (*ec2.DescribeSpotInstanceRequestsOutput, error) DescribeSpotInstanceRequests(*ec2.DescribeSpotInstanceRequestsInput) (*ec2.DescribeSpotInstanceRequestsOutput, error)
DescribeSpotPriceHistoryRequest(*ec2.DescribeSpotPriceHistoryInput) (*request.Request, *ec2.DescribeSpotPriceHistoryOutput)
DescribeSpotPriceHistory(*ec2.DescribeSpotPriceHistoryInput) (*ec2.DescribeSpotPriceHistoryOutput, error) DescribeSpotPriceHistory(*ec2.DescribeSpotPriceHistoryInput) (*ec2.DescribeSpotPriceHistoryOutput, error)
DescribeSpotPriceHistoryPages(*ec2.DescribeSpotPriceHistoryInput, func(*ec2.DescribeSpotPriceHistoryOutput, bool) bool) error
DescribeSubnetsRequest(*ec2.DescribeSubnetsInput) (*request.Request, *ec2.DescribeSubnetsOutput)
DescribeSubnets(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error) DescribeSubnets(*ec2.DescribeSubnetsInput) (*ec2.DescribeSubnetsOutput, error)
DescribeTagsRequest(*ec2.DescribeTagsInput) (*request.Request, *ec2.DescribeTagsOutput)
DescribeTags(*ec2.DescribeTagsInput) (*ec2.DescribeTagsOutput, error) DescribeTags(*ec2.DescribeTagsInput) (*ec2.DescribeTagsOutput, error)
DescribeVPCAttribute(*ec2.DescribeVPCAttributeInput) (*ec2.DescribeVPCAttributeOutput, error) DescribeVolumeAttributeRequest(*ec2.DescribeVolumeAttributeInput) (*request.Request, *ec2.DescribeVolumeAttributeOutput)
DescribeVPCClassicLink(*ec2.DescribeVPCClassicLinkInput) (*ec2.DescribeVPCClassicLinkOutput, error)
DescribeVPCEndpointServices(*ec2.DescribeVPCEndpointServicesInput) (*ec2.DescribeVPCEndpointServicesOutput, error)
DescribeVPCEndpoints(*ec2.DescribeVPCEndpointsInput) (*ec2.DescribeVPCEndpointsOutput, error)
DescribeVPCPeeringConnections(*ec2.DescribeVPCPeeringConnectionsInput) (*ec2.DescribeVPCPeeringConnectionsOutput, error)
DescribeVPCs(*ec2.DescribeVPCsInput) (*ec2.DescribeVPCsOutput, error)
DescribeVPNConnections(*ec2.DescribeVPNConnectionsInput) (*ec2.DescribeVPNConnectionsOutput, error)
DescribeVPNGateways(*ec2.DescribeVPNGatewaysInput) (*ec2.DescribeVPNGatewaysOutput, error)
DescribeVolumeAttribute(*ec2.DescribeVolumeAttributeInput) (*ec2.DescribeVolumeAttributeOutput, error) DescribeVolumeAttribute(*ec2.DescribeVolumeAttributeInput) (*ec2.DescribeVolumeAttributeOutput, error)
DescribeVolumeStatusRequest(*ec2.DescribeVolumeStatusInput) (*request.Request, *ec2.DescribeVolumeStatusOutput)
DescribeVolumeStatus(*ec2.DescribeVolumeStatusInput) (*ec2.DescribeVolumeStatusOutput, error) DescribeVolumeStatus(*ec2.DescribeVolumeStatusInput) (*ec2.DescribeVolumeStatusOutput, error)
DescribeVolumeStatusPages(*ec2.DescribeVolumeStatusInput, func(*ec2.DescribeVolumeStatusOutput, bool) bool) error
DescribeVolumesRequest(*ec2.DescribeVolumesInput) (*request.Request, *ec2.DescribeVolumesOutput)
DescribeVolumes(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) DescribeVolumes(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error)
DetachClassicLinkVPC(*ec2.DetachClassicLinkVPCInput) (*ec2.DetachClassicLinkVPCOutput, error) DescribeVolumesPages(*ec2.DescribeVolumesInput, func(*ec2.DescribeVolumesOutput, bool) bool) error
DescribeVpcAttributeRequest(*ec2.DescribeVpcAttributeInput) (*request.Request, *ec2.DescribeVpcAttributeOutput)
DescribeVpcAttribute(*ec2.DescribeVpcAttributeInput) (*ec2.DescribeVpcAttributeOutput, error)
DescribeVpcClassicLinkRequest(*ec2.DescribeVpcClassicLinkInput) (*request.Request, *ec2.DescribeVpcClassicLinkOutput)
DescribeVpcClassicLink(*ec2.DescribeVpcClassicLinkInput) (*ec2.DescribeVpcClassicLinkOutput, error)
DescribeVpcEndpointServicesRequest(*ec2.DescribeVpcEndpointServicesInput) (*request.Request, *ec2.DescribeVpcEndpointServicesOutput)
DescribeVpcEndpointServices(*ec2.DescribeVpcEndpointServicesInput) (*ec2.DescribeVpcEndpointServicesOutput, error)
DescribeVpcEndpointsRequest(*ec2.DescribeVpcEndpointsInput) (*request.Request, *ec2.DescribeVpcEndpointsOutput)
DescribeVpcEndpoints(*ec2.DescribeVpcEndpointsInput) (*ec2.DescribeVpcEndpointsOutput, error)
DescribeVpcPeeringConnectionsRequest(*ec2.DescribeVpcPeeringConnectionsInput) (*request.Request, *ec2.DescribeVpcPeeringConnectionsOutput)
DescribeVpcPeeringConnections(*ec2.DescribeVpcPeeringConnectionsInput) (*ec2.DescribeVpcPeeringConnectionsOutput, error)
DescribeVpcsRequest(*ec2.DescribeVpcsInput) (*request.Request, *ec2.DescribeVpcsOutput)
DescribeVpcs(*ec2.DescribeVpcsInput) (*ec2.DescribeVpcsOutput, error)
DescribeVpnConnectionsRequest(*ec2.DescribeVpnConnectionsInput) (*request.Request, *ec2.DescribeVpnConnectionsOutput)
DescribeVpnConnections(*ec2.DescribeVpnConnectionsInput) (*ec2.DescribeVpnConnectionsOutput, error)
DescribeVpnGatewaysRequest(*ec2.DescribeVpnGatewaysInput) (*request.Request, *ec2.DescribeVpnGatewaysOutput)
DescribeVpnGateways(*ec2.DescribeVpnGatewaysInput) (*ec2.DescribeVpnGatewaysOutput, error)
DetachClassicLinkVpcRequest(*ec2.DetachClassicLinkVpcInput) (*request.Request, *ec2.DetachClassicLinkVpcOutput)
DetachClassicLinkVpc(*ec2.DetachClassicLinkVpcInput) (*ec2.DetachClassicLinkVpcOutput, error)
DetachInternetGatewayRequest(*ec2.DetachInternetGatewayInput) (*request.Request, *ec2.DetachInternetGatewayOutput)
DetachInternetGateway(*ec2.DetachInternetGatewayInput) (*ec2.DetachInternetGatewayOutput, error) DetachInternetGateway(*ec2.DetachInternetGatewayInput) (*ec2.DetachInternetGatewayOutput, error)
DetachNetworkInterfaceRequest(*ec2.DetachNetworkInterfaceInput) (*request.Request, *ec2.DetachNetworkInterfaceOutput)
DetachNetworkInterface(*ec2.DetachNetworkInterfaceInput) (*ec2.DetachNetworkInterfaceOutput, error) DetachNetworkInterface(*ec2.DetachNetworkInterfaceInput) (*ec2.DetachNetworkInterfaceOutput, error)
DetachVPNGateway(*ec2.DetachVPNGatewayInput) (*ec2.DetachVPNGatewayOutput, error) DetachVolumeRequest(*ec2.DetachVolumeInput) (*request.Request, *ec2.VolumeAttachment)
DetachVolume(*ec2.DetachVolumeInput) (*ec2.VolumeAttachment, error) DetachVolume(*ec2.DetachVolumeInput) (*ec2.VolumeAttachment, error)
DisableVGWRoutePropagation(*ec2.DisableVGWRoutePropagationInput) (*ec2.DisableVGWRoutePropagationOutput, error) DetachVpnGatewayRequest(*ec2.DetachVpnGatewayInput) (*request.Request, *ec2.DetachVpnGatewayOutput)
DisableVPCClassicLink(*ec2.DisableVPCClassicLinkInput) (*ec2.DisableVPCClassicLinkOutput, error) DetachVpnGateway(*ec2.DetachVpnGatewayInput) (*ec2.DetachVpnGatewayOutput, error)
DisableVgwRoutePropagationRequest(*ec2.DisableVgwRoutePropagationInput) (*request.Request, *ec2.DisableVgwRoutePropagationOutput)
DisableVgwRoutePropagation(*ec2.DisableVgwRoutePropagationInput) (*ec2.DisableVgwRoutePropagationOutput, error)
DisableVpcClassicLinkRequest(*ec2.DisableVpcClassicLinkInput) (*request.Request, *ec2.DisableVpcClassicLinkOutput)
DisableVpcClassicLink(*ec2.DisableVpcClassicLinkInput) (*ec2.DisableVpcClassicLinkOutput, error)
DisassociateAddressRequest(*ec2.DisassociateAddressInput) (*request.Request, *ec2.DisassociateAddressOutput)
DisassociateAddress(*ec2.DisassociateAddressInput) (*ec2.DisassociateAddressOutput, error) DisassociateAddress(*ec2.DisassociateAddressInput) (*ec2.DisassociateAddressOutput, error)
DisassociateRouteTableRequest(*ec2.DisassociateRouteTableInput) (*request.Request, *ec2.DisassociateRouteTableOutput)
DisassociateRouteTable(*ec2.DisassociateRouteTableInput) (*ec2.DisassociateRouteTableOutput, error) DisassociateRouteTable(*ec2.DisassociateRouteTableInput) (*ec2.DisassociateRouteTableOutput, error)
EnableVGWRoutePropagation(*ec2.EnableVGWRoutePropagationInput) (*ec2.EnableVGWRoutePropagationOutput, error) EnableVgwRoutePropagationRequest(*ec2.EnableVgwRoutePropagationInput) (*request.Request, *ec2.EnableVgwRoutePropagationOutput)
EnableVPCClassicLink(*ec2.EnableVPCClassicLinkInput) (*ec2.EnableVPCClassicLinkOutput, error) EnableVgwRoutePropagation(*ec2.EnableVgwRoutePropagationInput) (*ec2.EnableVgwRoutePropagationOutput, error)
EnableVolumeIORequest(*ec2.EnableVolumeIOInput) (*request.Request, *ec2.EnableVolumeIOOutput)
EnableVolumeIO(*ec2.EnableVolumeIOInput) (*ec2.EnableVolumeIOOutput, error) EnableVolumeIO(*ec2.EnableVolumeIOInput) (*ec2.EnableVolumeIOOutput, error)
EnableVpcClassicLinkRequest(*ec2.EnableVpcClassicLinkInput) (*request.Request, *ec2.EnableVpcClassicLinkOutput)
EnableVpcClassicLink(*ec2.EnableVpcClassicLinkInput) (*ec2.EnableVpcClassicLinkOutput, error)
GetConsoleOutputRequest(*ec2.GetConsoleOutputInput) (*request.Request, *ec2.GetConsoleOutputOutput)
GetConsoleOutput(*ec2.GetConsoleOutputInput) (*ec2.GetConsoleOutputOutput, error) GetConsoleOutput(*ec2.GetConsoleOutputInput) (*ec2.GetConsoleOutputOutput, error)
GetPasswordDataRequest(*ec2.GetPasswordDataInput) (*request.Request, *ec2.GetPasswordDataOutput)
GetPasswordData(*ec2.GetPasswordDataInput) (*ec2.GetPasswordDataOutput, error) GetPasswordData(*ec2.GetPasswordDataInput) (*ec2.GetPasswordDataOutput, error)
ImportImageRequest(*ec2.ImportImageInput) (*request.Request, *ec2.ImportImageOutput)
ImportImage(*ec2.ImportImageInput) (*ec2.ImportImageOutput, error) ImportImage(*ec2.ImportImageInput) (*ec2.ImportImageOutput, error)
ImportInstanceRequest(*ec2.ImportInstanceInput) (*request.Request, *ec2.ImportInstanceOutput)
ImportInstance(*ec2.ImportInstanceInput) (*ec2.ImportInstanceOutput, error) ImportInstance(*ec2.ImportInstanceInput) (*ec2.ImportInstanceOutput, error)
ImportKeyPairRequest(*ec2.ImportKeyPairInput) (*request.Request, *ec2.ImportKeyPairOutput)
ImportKeyPair(*ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error) ImportKeyPair(*ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error)
ImportSnapshotRequest(*ec2.ImportSnapshotInput) (*request.Request, *ec2.ImportSnapshotOutput)
ImportSnapshot(*ec2.ImportSnapshotInput) (*ec2.ImportSnapshotOutput, error) ImportSnapshot(*ec2.ImportSnapshotInput) (*ec2.ImportSnapshotOutput, error)
ImportVolumeRequest(*ec2.ImportVolumeInput) (*request.Request, *ec2.ImportVolumeOutput)
ImportVolume(*ec2.ImportVolumeInput) (*ec2.ImportVolumeOutput, error) ImportVolume(*ec2.ImportVolumeInput) (*ec2.ImportVolumeOutput, error)
ModifyImageAttributeRequest(*ec2.ModifyImageAttributeInput) (*request.Request, *ec2.ModifyImageAttributeOutput)
ModifyImageAttribute(*ec2.ModifyImageAttributeInput) (*ec2.ModifyImageAttributeOutput, error) ModifyImageAttribute(*ec2.ModifyImageAttributeInput) (*ec2.ModifyImageAttributeOutput, error)
ModifyInstanceAttributeRequest(*ec2.ModifyInstanceAttributeInput) (*request.Request, *ec2.ModifyInstanceAttributeOutput)
ModifyInstanceAttribute(*ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) ModifyInstanceAttribute(*ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error)
ModifyNetworkInterfaceAttributeRequest(*ec2.ModifyNetworkInterfaceAttributeInput) (*request.Request, *ec2.ModifyNetworkInterfaceAttributeOutput)
ModifyNetworkInterfaceAttribute(*ec2.ModifyNetworkInterfaceAttributeInput) (*ec2.ModifyNetworkInterfaceAttributeOutput, error) ModifyNetworkInterfaceAttribute(*ec2.ModifyNetworkInterfaceAttributeInput) (*ec2.ModifyNetworkInterfaceAttributeOutput, error)
ModifyReservedInstancesRequest(*ec2.ModifyReservedInstancesInput) (*request.Request, *ec2.ModifyReservedInstancesOutput)
ModifyReservedInstances(*ec2.ModifyReservedInstancesInput) (*ec2.ModifyReservedInstancesOutput, error) ModifyReservedInstances(*ec2.ModifyReservedInstancesInput) (*ec2.ModifyReservedInstancesOutput, error)
ModifySnapshotAttributeRequest(*ec2.ModifySnapshotAttributeInput) (*request.Request, *ec2.ModifySnapshotAttributeOutput)
ModifySnapshotAttribute(*ec2.ModifySnapshotAttributeInput) (*ec2.ModifySnapshotAttributeOutput, error) ModifySnapshotAttribute(*ec2.ModifySnapshotAttributeInput) (*ec2.ModifySnapshotAttributeOutput, error)
ModifySubnetAttributeRequest(*ec2.ModifySubnetAttributeInput) (*request.Request, *ec2.ModifySubnetAttributeOutput)
ModifySubnetAttribute(*ec2.ModifySubnetAttributeInput) (*ec2.ModifySubnetAttributeOutput, error) ModifySubnetAttribute(*ec2.ModifySubnetAttributeInput) (*ec2.ModifySubnetAttributeOutput, error)
ModifyVPCAttribute(*ec2.ModifyVPCAttributeInput) (*ec2.ModifyVPCAttributeOutput, error) ModifyVolumeAttributeRequest(*ec2.ModifyVolumeAttributeInput) (*request.Request, *ec2.ModifyVolumeAttributeOutput)
ModifyVPCEndpoint(*ec2.ModifyVPCEndpointInput) (*ec2.ModifyVPCEndpointOutput, error)
ModifyVolumeAttribute(*ec2.ModifyVolumeAttributeInput) (*ec2.ModifyVolumeAttributeOutput, error) ModifyVolumeAttribute(*ec2.ModifyVolumeAttributeInput) (*ec2.ModifyVolumeAttributeOutput, error)
ModifyVpcAttributeRequest(*ec2.ModifyVpcAttributeInput) (*request.Request, *ec2.ModifyVpcAttributeOutput)
ModifyVpcAttribute(*ec2.ModifyVpcAttributeInput) (*ec2.ModifyVpcAttributeOutput, error)
ModifyVpcEndpointRequest(*ec2.ModifyVpcEndpointInput) (*request.Request, *ec2.ModifyVpcEndpointOutput)
ModifyVpcEndpoint(*ec2.ModifyVpcEndpointInput) (*ec2.ModifyVpcEndpointOutput, error)
MonitorInstancesRequest(*ec2.MonitorInstancesInput) (*request.Request, *ec2.MonitorInstancesOutput)
MonitorInstances(*ec2.MonitorInstancesInput) (*ec2.MonitorInstancesOutput, error) MonitorInstances(*ec2.MonitorInstancesInput) (*ec2.MonitorInstancesOutput, error)
MoveAddressToVPC(*ec2.MoveAddressToVPCInput) (*ec2.MoveAddressToVPCOutput, error) MoveAddressToVpcRequest(*ec2.MoveAddressToVpcInput) (*request.Request, *ec2.MoveAddressToVpcOutput)
MoveAddressToVpc(*ec2.MoveAddressToVpcInput) (*ec2.MoveAddressToVpcOutput, error)
PurchaseReservedInstancesOfferingRequest(*ec2.PurchaseReservedInstancesOfferingInput) (*request.Request, *ec2.PurchaseReservedInstancesOfferingOutput)
PurchaseReservedInstancesOffering(*ec2.PurchaseReservedInstancesOfferingInput) (*ec2.PurchaseReservedInstancesOfferingOutput, error) PurchaseReservedInstancesOffering(*ec2.PurchaseReservedInstancesOfferingInput) (*ec2.PurchaseReservedInstancesOfferingOutput, error)
RebootInstancesRequest(*ec2.RebootInstancesInput) (*request.Request, *ec2.RebootInstancesOutput)
RebootInstances(*ec2.RebootInstancesInput) (*ec2.RebootInstancesOutput, error) RebootInstances(*ec2.RebootInstancesInput) (*ec2.RebootInstancesOutput, error)
RegisterImageRequest(*ec2.RegisterImageInput) (*request.Request, *ec2.RegisterImageOutput)
RegisterImage(*ec2.RegisterImageInput) (*ec2.RegisterImageOutput, error) RegisterImage(*ec2.RegisterImageInput) (*ec2.RegisterImageOutput, error)
RejectVPCPeeringConnection(*ec2.RejectVPCPeeringConnectionInput) (*ec2.RejectVPCPeeringConnectionOutput, error) RejectVpcPeeringConnectionRequest(*ec2.RejectVpcPeeringConnectionInput) (*request.Request, *ec2.RejectVpcPeeringConnectionOutput)
RejectVpcPeeringConnection(*ec2.RejectVpcPeeringConnectionInput) (*ec2.RejectVpcPeeringConnectionOutput, error)
ReleaseAddressRequest(*ec2.ReleaseAddressInput) (*request.Request, *ec2.ReleaseAddressOutput)
ReleaseAddress(*ec2.ReleaseAddressInput) (*ec2.ReleaseAddressOutput, error) ReleaseAddress(*ec2.ReleaseAddressInput) (*ec2.ReleaseAddressOutput, error)
ReplaceNetworkACLAssociation(*ec2.ReplaceNetworkACLAssociationInput) (*ec2.ReplaceNetworkACLAssociationOutput, error) ReplaceNetworkAclAssociationRequest(*ec2.ReplaceNetworkAclAssociationInput) (*request.Request, *ec2.ReplaceNetworkAclAssociationOutput)
ReplaceNetworkACLEntry(*ec2.ReplaceNetworkACLEntryInput) (*ec2.ReplaceNetworkACLEntryOutput, error) ReplaceNetworkAclAssociation(*ec2.ReplaceNetworkAclAssociationInput) (*ec2.ReplaceNetworkAclAssociationOutput, error)
ReplaceNetworkAclEntryRequest(*ec2.ReplaceNetworkAclEntryInput) (*request.Request, *ec2.ReplaceNetworkAclEntryOutput)
ReplaceNetworkAclEntry(*ec2.ReplaceNetworkAclEntryInput) (*ec2.ReplaceNetworkAclEntryOutput, error)
ReplaceRouteRequest(*ec2.ReplaceRouteInput) (*request.Request, *ec2.ReplaceRouteOutput)
ReplaceRoute(*ec2.ReplaceRouteInput) (*ec2.ReplaceRouteOutput, error) ReplaceRoute(*ec2.ReplaceRouteInput) (*ec2.ReplaceRouteOutput, error)
ReplaceRouteTableAssociationRequest(*ec2.ReplaceRouteTableAssociationInput) (*request.Request, *ec2.ReplaceRouteTableAssociationOutput)
ReplaceRouteTableAssociation(*ec2.ReplaceRouteTableAssociationInput) (*ec2.ReplaceRouteTableAssociationOutput, error) ReplaceRouteTableAssociation(*ec2.ReplaceRouteTableAssociationInput) (*ec2.ReplaceRouteTableAssociationOutput, error)
ReportInstanceStatusRequest(*ec2.ReportInstanceStatusInput) (*request.Request, *ec2.ReportInstanceStatusOutput)
ReportInstanceStatus(*ec2.ReportInstanceStatusInput) (*ec2.ReportInstanceStatusOutput, error) ReportInstanceStatus(*ec2.ReportInstanceStatusInput) (*ec2.ReportInstanceStatusOutput, error)
RequestSpotFleetRequest(*ec2.RequestSpotFleetInput) (*request.Request, *ec2.RequestSpotFleetOutput)
RequestSpotFleet(*ec2.RequestSpotFleetInput) (*ec2.RequestSpotFleetOutput, error) RequestSpotFleet(*ec2.RequestSpotFleetInput) (*ec2.RequestSpotFleetOutput, error)
RequestSpotInstancesRequest(*ec2.RequestSpotInstancesInput) (*request.Request, *ec2.RequestSpotInstancesOutput)
RequestSpotInstances(*ec2.RequestSpotInstancesInput) (*ec2.RequestSpotInstancesOutput, error) RequestSpotInstances(*ec2.RequestSpotInstancesInput) (*ec2.RequestSpotInstancesOutput, error)
ResetImageAttributeRequest(*ec2.ResetImageAttributeInput) (*request.Request, *ec2.ResetImageAttributeOutput)
ResetImageAttribute(*ec2.ResetImageAttributeInput) (*ec2.ResetImageAttributeOutput, error) ResetImageAttribute(*ec2.ResetImageAttributeInput) (*ec2.ResetImageAttributeOutput, error)
ResetInstanceAttributeRequest(*ec2.ResetInstanceAttributeInput) (*request.Request, *ec2.ResetInstanceAttributeOutput)
ResetInstanceAttribute(*ec2.ResetInstanceAttributeInput) (*ec2.ResetInstanceAttributeOutput, error) ResetInstanceAttribute(*ec2.ResetInstanceAttributeInput) (*ec2.ResetInstanceAttributeOutput, error)
ResetNetworkInterfaceAttributeRequest(*ec2.ResetNetworkInterfaceAttributeInput) (*request.Request, *ec2.ResetNetworkInterfaceAttributeOutput)
ResetNetworkInterfaceAttribute(*ec2.ResetNetworkInterfaceAttributeInput) (*ec2.ResetNetworkInterfaceAttributeOutput, error) ResetNetworkInterfaceAttribute(*ec2.ResetNetworkInterfaceAttributeInput) (*ec2.ResetNetworkInterfaceAttributeOutput, error)
ResetSnapshotAttributeRequest(*ec2.ResetSnapshotAttributeInput) (*request.Request, *ec2.ResetSnapshotAttributeOutput)
ResetSnapshotAttribute(*ec2.ResetSnapshotAttributeInput) (*ec2.ResetSnapshotAttributeOutput, error) ResetSnapshotAttribute(*ec2.ResetSnapshotAttributeInput) (*ec2.ResetSnapshotAttributeOutput, error)
RestoreAddressToClassicRequest(*ec2.RestoreAddressToClassicInput) (*request.Request, *ec2.RestoreAddressToClassicOutput)
RestoreAddressToClassic(*ec2.RestoreAddressToClassicInput) (*ec2.RestoreAddressToClassicOutput, error) RestoreAddressToClassic(*ec2.RestoreAddressToClassicInput) (*ec2.RestoreAddressToClassicOutput, error)
RevokeSecurityGroupEgressRequest(*ec2.RevokeSecurityGroupEgressInput) (*request.Request, *ec2.RevokeSecurityGroupEgressOutput)
RevokeSecurityGroupEgress(*ec2.RevokeSecurityGroupEgressInput) (*ec2.RevokeSecurityGroupEgressOutput, error) RevokeSecurityGroupEgress(*ec2.RevokeSecurityGroupEgressInput) (*ec2.RevokeSecurityGroupEgressOutput, error)
RevokeSecurityGroupIngressRequest(*ec2.RevokeSecurityGroupIngressInput) (*request.Request, *ec2.RevokeSecurityGroupIngressOutput)
RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error)
RunInstancesRequest(*ec2.RunInstancesInput) (*request.Request, *ec2.Reservation)
RunInstances(*ec2.RunInstancesInput) (*ec2.Reservation, error) RunInstances(*ec2.RunInstancesInput) (*ec2.Reservation, error)
StartInstancesRequest(*ec2.StartInstancesInput) (*request.Request, *ec2.StartInstancesOutput)
StartInstances(*ec2.StartInstancesInput) (*ec2.StartInstancesOutput, error) StartInstances(*ec2.StartInstancesInput) (*ec2.StartInstancesOutput, error)
StopInstancesRequest(*ec2.StopInstancesInput) (*request.Request, *ec2.StopInstancesOutput)
StopInstances(*ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error) StopInstances(*ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error)
TerminateInstancesRequest(*ec2.TerminateInstancesInput) (*request.Request, *ec2.TerminateInstancesOutput)
TerminateInstances(*ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) TerminateInstances(*ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error)
UnassignPrivateIPAddresses(*ec2.UnassignPrivateIPAddressesInput) (*ec2.UnassignPrivateIPAddressesOutput, error) UnassignPrivateIpAddressesRequest(*ec2.UnassignPrivateIpAddressesInput) (*request.Request, *ec2.UnassignPrivateIpAddressesOutput)
UnassignPrivateIpAddresses(*ec2.UnassignPrivateIpAddressesInput) (*ec2.UnassignPrivateIpAddressesOutput, error)
UnmonitorInstancesRequest(*ec2.UnmonitorInstancesInput) (*request.Request, *ec2.UnmonitorInstancesOutput)
UnmonitorInstances(*ec2.UnmonitorInstancesInput) (*ec2.UnmonitorInstancesOutput, error) UnmonitorInstances(*ec2.UnmonitorInstancesInput) (*ec2.UnmonitorInstancesOutput, error)
} }

File diff suppressed because it is too large Load Diff

View File

@@ -4,27 +4,36 @@ package ec2
import ( import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/ec2query" "github.com/aws/aws-sdk-go/internal/protocol/ec2query"
"github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/signer/v4"
) )
// EC2 is a client for Amazon EC2. // Amazon Elastic Compute Cloud (Amazon EC2) provides resizable computing capacity
// in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your
// need to invest in hardware up front, so you can develop and deploy applications
// faster.
type EC2 struct { type EC2 struct {
*aws.Service *service.Service
} }
// Used for custom service initialization logic // Used for custom service initialization logic
var initService func(*aws.Service) var initService func(*service.Service)
// Used for custom request initialization logic // Used for custom request initialization logic
var initRequest func(*aws.Request) var initRequest func(*request.Request)
// New returns a new EC2 client. // New returns a new EC2 client.
func New(config *aws.Config) *EC2 { func New(config *aws.Config) *EC2 {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "ec2", ServiceName: "ec2",
APIVersion: "2015-04-15", APIVersion: "2015-04-15",
},
} }
service.Initialize() service.Initialize()
@@ -45,8 +54,8 @@ func New(config *aws.Config) *EC2 {
// newRequest creates a new request for a EC2 operation and runs any // newRequest creates a new request for a EC2 operation and runs any
// custom request initialization. // custom request initialization.
func (c *EC2) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *EC2) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
// Run custom request initialization if present // Run custom request initialization if present
if initRequest != nil { if initRequest != nil {

File diff suppressed because it is too large Load Diff

View File

@@ -4,64 +4,123 @@
package elbiface package elbiface
import ( import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/elb" "github.com/aws/aws-sdk-go/service/elb"
) )
// ELBAPI is the interface type for elb.ELB. // ELBAPI is the interface type for elb.ELB.
type ELBAPI interface { type ELBAPI interface {
AddTagsRequest(*elb.AddTagsInput) (*request.Request, *elb.AddTagsOutput)
AddTags(*elb.AddTagsInput) (*elb.AddTagsOutput, error) AddTags(*elb.AddTagsInput) (*elb.AddTagsOutput, error)
ApplySecurityGroupsToLoadBalancerRequest(*elb.ApplySecurityGroupsToLoadBalancerInput) (*request.Request, *elb.ApplySecurityGroupsToLoadBalancerOutput)
ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error) ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error)
AttachLoadBalancerToSubnetsRequest(*elb.AttachLoadBalancerToSubnetsInput) (*request.Request, *elb.AttachLoadBalancerToSubnetsOutput)
AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error) AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error)
ConfigureHealthCheckRequest(*elb.ConfigureHealthCheckInput) (*request.Request, *elb.ConfigureHealthCheckOutput)
ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error) ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error)
CreateAppCookieStickinessPolicyRequest(*elb.CreateAppCookieStickinessPolicyInput) (*request.Request, *elb.CreateAppCookieStickinessPolicyOutput)
CreateAppCookieStickinessPolicy(*elb.CreateAppCookieStickinessPolicyInput) (*elb.CreateAppCookieStickinessPolicyOutput, error) CreateAppCookieStickinessPolicy(*elb.CreateAppCookieStickinessPolicyInput) (*elb.CreateAppCookieStickinessPolicyOutput, error)
CreateLBCookieStickinessPolicyRequest(*elb.CreateLBCookieStickinessPolicyInput) (*request.Request, *elb.CreateLBCookieStickinessPolicyOutput)
CreateLBCookieStickinessPolicy(*elb.CreateLBCookieStickinessPolicyInput) (*elb.CreateLBCookieStickinessPolicyOutput, error) CreateLBCookieStickinessPolicy(*elb.CreateLBCookieStickinessPolicyInput) (*elb.CreateLBCookieStickinessPolicyOutput, error)
CreateLoadBalancerRequest(*elb.CreateLoadBalancerInput) (*request.Request, *elb.CreateLoadBalancerOutput)
CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error) CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error)
CreateLoadBalancerListenersRequest(*elb.CreateLoadBalancerListenersInput) (*request.Request, *elb.CreateLoadBalancerListenersOutput)
CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error) CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error)
CreateLoadBalancerPolicyRequest(*elb.CreateLoadBalancerPolicyInput) (*request.Request, *elb.CreateLoadBalancerPolicyOutput)
CreateLoadBalancerPolicy(*elb.CreateLoadBalancerPolicyInput) (*elb.CreateLoadBalancerPolicyOutput, error) CreateLoadBalancerPolicy(*elb.CreateLoadBalancerPolicyInput) (*elb.CreateLoadBalancerPolicyOutput, error)
DeleteLoadBalancerRequest(*elb.DeleteLoadBalancerInput) (*request.Request, *elb.DeleteLoadBalancerOutput)
DeleteLoadBalancer(*elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error) DeleteLoadBalancer(*elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error)
DeleteLoadBalancerListenersRequest(*elb.DeleteLoadBalancerListenersInput) (*request.Request, *elb.DeleteLoadBalancerListenersOutput)
DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error) DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error)
DeleteLoadBalancerPolicyRequest(*elb.DeleteLoadBalancerPolicyInput) (*request.Request, *elb.DeleteLoadBalancerPolicyOutput)
DeleteLoadBalancerPolicy(*elb.DeleteLoadBalancerPolicyInput) (*elb.DeleteLoadBalancerPolicyOutput, error) DeleteLoadBalancerPolicy(*elb.DeleteLoadBalancerPolicyInput) (*elb.DeleteLoadBalancerPolicyOutput, error)
DeregisterInstancesFromLoadBalancerRequest(*elb.DeregisterInstancesFromLoadBalancerInput) (*request.Request, *elb.DeregisterInstancesFromLoadBalancerOutput)
DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error) DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error)
DescribeInstanceHealthRequest(*elb.DescribeInstanceHealthInput) (*request.Request, *elb.DescribeInstanceHealthOutput)
DescribeInstanceHealth(*elb.DescribeInstanceHealthInput) (*elb.DescribeInstanceHealthOutput, error) DescribeInstanceHealth(*elb.DescribeInstanceHealthInput) (*elb.DescribeInstanceHealthOutput, error)
DescribeLoadBalancerAttributesRequest(*elb.DescribeLoadBalancerAttributesInput) (*request.Request, *elb.DescribeLoadBalancerAttributesOutput)
DescribeLoadBalancerAttributes(*elb.DescribeLoadBalancerAttributesInput) (*elb.DescribeLoadBalancerAttributesOutput, error) DescribeLoadBalancerAttributes(*elb.DescribeLoadBalancerAttributesInput) (*elb.DescribeLoadBalancerAttributesOutput, error)
DescribeLoadBalancerPoliciesRequest(*elb.DescribeLoadBalancerPoliciesInput) (*request.Request, *elb.DescribeLoadBalancerPoliciesOutput)
DescribeLoadBalancerPolicies(*elb.DescribeLoadBalancerPoliciesInput) (*elb.DescribeLoadBalancerPoliciesOutput, error) DescribeLoadBalancerPolicies(*elb.DescribeLoadBalancerPoliciesInput) (*elb.DescribeLoadBalancerPoliciesOutput, error)
DescribeLoadBalancerPolicyTypesRequest(*elb.DescribeLoadBalancerPolicyTypesInput) (*request.Request, *elb.DescribeLoadBalancerPolicyTypesOutput)
DescribeLoadBalancerPolicyTypes(*elb.DescribeLoadBalancerPolicyTypesInput) (*elb.DescribeLoadBalancerPolicyTypesOutput, error) DescribeLoadBalancerPolicyTypes(*elb.DescribeLoadBalancerPolicyTypesInput) (*elb.DescribeLoadBalancerPolicyTypesOutput, error)
DescribeLoadBalancersRequest(*elb.DescribeLoadBalancersInput) (*request.Request, *elb.DescribeLoadBalancersOutput)
DescribeLoadBalancers(*elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) DescribeLoadBalancers(*elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error)
DescribeLoadBalancersPages(*elb.DescribeLoadBalancersInput, func(*elb.DescribeLoadBalancersOutput, bool) bool) error
DescribeTagsRequest(*elb.DescribeTagsInput) (*request.Request, *elb.DescribeTagsOutput)
DescribeTags(*elb.DescribeTagsInput) (*elb.DescribeTagsOutput, error) DescribeTags(*elb.DescribeTagsInput) (*elb.DescribeTagsOutput, error)
DetachLoadBalancerFromSubnetsRequest(*elb.DetachLoadBalancerFromSubnetsInput) (*request.Request, *elb.DetachLoadBalancerFromSubnetsOutput)
DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error) DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error)
DisableAvailabilityZonesForLoadBalancerRequest(*elb.DisableAvailabilityZonesForLoadBalancerInput) (*request.Request, *elb.DisableAvailabilityZonesForLoadBalancerOutput)
DisableAvailabilityZonesForLoadBalancer(*elb.DisableAvailabilityZonesForLoadBalancerInput) (*elb.DisableAvailabilityZonesForLoadBalancerOutput, error) DisableAvailabilityZonesForLoadBalancer(*elb.DisableAvailabilityZonesForLoadBalancerInput) (*elb.DisableAvailabilityZonesForLoadBalancerOutput, error)
EnableAvailabilityZonesForLoadBalancerRequest(*elb.EnableAvailabilityZonesForLoadBalancerInput) (*request.Request, *elb.EnableAvailabilityZonesForLoadBalancerOutput)
EnableAvailabilityZonesForLoadBalancer(*elb.EnableAvailabilityZonesForLoadBalancerInput) (*elb.EnableAvailabilityZonesForLoadBalancerOutput, error) EnableAvailabilityZonesForLoadBalancer(*elb.EnableAvailabilityZonesForLoadBalancerInput) (*elb.EnableAvailabilityZonesForLoadBalancerOutput, error)
ModifyLoadBalancerAttributesRequest(*elb.ModifyLoadBalancerAttributesInput) (*request.Request, *elb.ModifyLoadBalancerAttributesOutput)
ModifyLoadBalancerAttributes(*elb.ModifyLoadBalancerAttributesInput) (*elb.ModifyLoadBalancerAttributesOutput, error) ModifyLoadBalancerAttributes(*elb.ModifyLoadBalancerAttributesInput) (*elb.ModifyLoadBalancerAttributesOutput, error)
RegisterInstancesWithLoadBalancerRequest(*elb.RegisterInstancesWithLoadBalancerInput) (*request.Request, *elb.RegisterInstancesWithLoadBalancerOutput)
RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error) RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error)
RemoveTagsRequest(*elb.RemoveTagsInput) (*request.Request, *elb.RemoveTagsOutput)
RemoveTags(*elb.RemoveTagsInput) (*elb.RemoveTagsOutput, error) RemoveTags(*elb.RemoveTagsInput) (*elb.RemoveTagsOutput, error)
SetLoadBalancerListenerSSLCertificateRequest(*elb.SetLoadBalancerListenerSSLCertificateInput) (*request.Request, *elb.SetLoadBalancerListenerSSLCertificateOutput)
SetLoadBalancerListenerSSLCertificate(*elb.SetLoadBalancerListenerSSLCertificateInput) (*elb.SetLoadBalancerListenerSSLCertificateOutput, error) SetLoadBalancerListenerSSLCertificate(*elb.SetLoadBalancerListenerSSLCertificateInput) (*elb.SetLoadBalancerListenerSSLCertificateOutput, error)
SetLoadBalancerPoliciesForBackendServerRequest(*elb.SetLoadBalancerPoliciesForBackendServerInput) (*request.Request, *elb.SetLoadBalancerPoliciesForBackendServerOutput)
SetLoadBalancerPoliciesForBackendServer(*elb.SetLoadBalancerPoliciesForBackendServerInput) (*elb.SetLoadBalancerPoliciesForBackendServerOutput, error) SetLoadBalancerPoliciesForBackendServer(*elb.SetLoadBalancerPoliciesForBackendServerInput) (*elb.SetLoadBalancerPoliciesForBackendServerOutput, error)
SetLoadBalancerPoliciesOfListenerRequest(*elb.SetLoadBalancerPoliciesOfListenerInput) (*request.Request, *elb.SetLoadBalancerPoliciesOfListenerOutput)
SetLoadBalancerPoliciesOfListener(*elb.SetLoadBalancerPoliciesOfListenerInput) (*elb.SetLoadBalancerPoliciesOfListenerOutput, error) SetLoadBalancerPoliciesOfListener(*elb.SetLoadBalancerPoliciesOfListenerInput) (*elb.SetLoadBalancerPoliciesOfListenerOutput, error)
} }

View File

@@ -8,8 +8,6 @@ import (
"time" "time"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/service/elb" "github.com/aws/aws-sdk-go/service/elb"
) )
@@ -25,7 +23,7 @@ func ExampleELB_AddTags() {
// More values... // More values...
}, },
Tags: []*elb.Tag{ // Required Tags: []*elb.Tag{ // Required
&elb.Tag{ // Required { // Required
Key: aws.String("TagKey"), // Required Key: aws.String("TagKey"), // Required
Value: aws.String("TagValue"), Value: aws.String("TagValue"),
}, },
@@ -35,22 +33,14 @@ func ExampleELB_AddTags() {
resp, err := svc.AddTags(params) resp, err := svc.AddTags(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_ApplySecurityGroupsToLoadBalancer() { func ExampleELB_ApplySecurityGroupsToLoadBalancer() {
@@ -66,22 +56,14 @@ func ExampleELB_ApplySecurityGroupsToLoadBalancer() {
resp, err := svc.ApplySecurityGroupsToLoadBalancer(params) resp, err := svc.ApplySecurityGroupsToLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_AttachLoadBalancerToSubnets() { func ExampleELB_AttachLoadBalancerToSubnets() {
@@ -97,22 +79,14 @@ func ExampleELB_AttachLoadBalancerToSubnets() {
resp, err := svc.AttachLoadBalancerToSubnets(params) resp, err := svc.AttachLoadBalancerToSubnets(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_ConfigureHealthCheck() { func ExampleELB_ConfigureHealthCheck() {
@@ -120,33 +94,25 @@ func ExampleELB_ConfigureHealthCheck() {
params := &elb.ConfigureHealthCheckInput{ params := &elb.ConfigureHealthCheckInput{
HealthCheck: &elb.HealthCheck{ // Required HealthCheck: &elb.HealthCheck{ // Required
HealthyThreshold: aws.Long(1), // Required HealthyThreshold: aws.Int64(1), // Required
Interval: aws.Long(1), // Required Interval: aws.Int64(1), // Required
Target: aws.String("HealthCheckTarget"), // Required Target: aws.String("HealthCheckTarget"), // Required
Timeout: aws.Long(1), // Required Timeout: aws.Int64(1), // Required
UnhealthyThreshold: aws.Long(1), // Required UnhealthyThreshold: aws.Int64(1), // Required
}, },
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
} }
resp, err := svc.ConfigureHealthCheck(params) resp, err := svc.ConfigureHealthCheck(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_CreateAppCookieStickinessPolicy() { func ExampleELB_CreateAppCookieStickinessPolicy() {
@@ -160,22 +126,14 @@ func ExampleELB_CreateAppCookieStickinessPolicy() {
resp, err := svc.CreateAppCookieStickinessPolicy(params) resp, err := svc.CreateAppCookieStickinessPolicy(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_CreateLBCookieStickinessPolicy() { func ExampleELB_CreateLBCookieStickinessPolicy() {
@@ -184,27 +142,19 @@ func ExampleELB_CreateLBCookieStickinessPolicy() {
params := &elb.CreateLBCookieStickinessPolicyInput{ params := &elb.CreateLBCookieStickinessPolicyInput{
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
PolicyName: aws.String("PolicyName"), // Required PolicyName: aws.String("PolicyName"), // Required
CookieExpirationPeriod: aws.Long(1), CookieExpirationPeriod: aws.Int64(1),
} }
resp, err := svc.CreateLBCookieStickinessPolicy(params) resp, err := svc.CreateLBCookieStickinessPolicy(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_CreateLoadBalancer() { func ExampleELB_CreateLoadBalancer() {
@@ -212,12 +162,12 @@ func ExampleELB_CreateLoadBalancer() {
params := &elb.CreateLoadBalancerInput{ params := &elb.CreateLoadBalancerInput{
Listeners: []*elb.Listener{ // Required Listeners: []*elb.Listener{ // Required
&elb.Listener{ // Required { // Required
InstancePort: aws.Long(1), // Required InstancePort: aws.Int64(1), // Required
LoadBalancerPort: aws.Long(1), // Required LoadBalancerPort: aws.Int64(1), // Required
Protocol: aws.String("Protocol"), // Required Protocol: aws.String("Protocol"), // Required
InstanceProtocol: aws.String("Protocol"), InstanceProtocol: aws.String("Protocol"),
SSLCertificateID: aws.String("SSLCertificateId"), SSLCertificateId: aws.String("SSLCertificateId"),
}, },
// More values... // More values...
}, },
@@ -236,7 +186,7 @@ func ExampleELB_CreateLoadBalancer() {
// More values... // More values...
}, },
Tags: []*elb.Tag{ Tags: []*elb.Tag{
&elb.Tag{ // Required { // Required
Key: aws.String("TagKey"), // Required Key: aws.String("TagKey"), // Required
Value: aws.String("TagValue"), Value: aws.String("TagValue"),
}, },
@@ -246,22 +196,14 @@ func ExampleELB_CreateLoadBalancer() {
resp, err := svc.CreateLoadBalancer(params) resp, err := svc.CreateLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_CreateLoadBalancerListeners() { func ExampleELB_CreateLoadBalancerListeners() {
@@ -269,12 +211,12 @@ func ExampleELB_CreateLoadBalancerListeners() {
params := &elb.CreateLoadBalancerListenersInput{ params := &elb.CreateLoadBalancerListenersInput{
Listeners: []*elb.Listener{ // Required Listeners: []*elb.Listener{ // Required
&elb.Listener{ // Required { // Required
InstancePort: aws.Long(1), // Required InstancePort: aws.Int64(1), // Required
LoadBalancerPort: aws.Long(1), // Required LoadBalancerPort: aws.Int64(1), // Required
Protocol: aws.String("Protocol"), // Required Protocol: aws.String("Protocol"), // Required
InstanceProtocol: aws.String("Protocol"), InstanceProtocol: aws.String("Protocol"),
SSLCertificateID: aws.String("SSLCertificateId"), SSLCertificateId: aws.String("SSLCertificateId"),
}, },
// More values... // More values...
}, },
@@ -283,22 +225,14 @@ func ExampleELB_CreateLoadBalancerListeners() {
resp, err := svc.CreateLoadBalancerListeners(params) resp, err := svc.CreateLoadBalancerListeners(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_CreateLoadBalancerPolicy() { func ExampleELB_CreateLoadBalancerPolicy() {
@@ -309,7 +243,7 @@ func ExampleELB_CreateLoadBalancerPolicy() {
PolicyName: aws.String("PolicyName"), // Required PolicyName: aws.String("PolicyName"), // Required
PolicyTypeName: aws.String("PolicyTypeName"), // Required PolicyTypeName: aws.String("PolicyTypeName"), // Required
PolicyAttributes: []*elb.PolicyAttribute{ PolicyAttributes: []*elb.PolicyAttribute{
&elb.PolicyAttribute{ // Required { // Required
AttributeName: aws.String("AttributeName"), AttributeName: aws.String("AttributeName"),
AttributeValue: aws.String("AttributeValue"), AttributeValue: aws.String("AttributeValue"),
}, },
@@ -319,22 +253,14 @@ func ExampleELB_CreateLoadBalancerPolicy() {
resp, err := svc.CreateLoadBalancerPolicy(params) resp, err := svc.CreateLoadBalancerPolicy(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DeleteLoadBalancer() { func ExampleELB_DeleteLoadBalancer() {
@@ -346,22 +272,14 @@ func ExampleELB_DeleteLoadBalancer() {
resp, err := svc.DeleteLoadBalancer(params) resp, err := svc.DeleteLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DeleteLoadBalancerListeners() { func ExampleELB_DeleteLoadBalancerListeners() {
@@ -370,29 +288,21 @@ func ExampleELB_DeleteLoadBalancerListeners() {
params := &elb.DeleteLoadBalancerListenersInput{ params := &elb.DeleteLoadBalancerListenersInput{
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
LoadBalancerPorts: []*int64{ // Required LoadBalancerPorts: []*int64{ // Required
aws.Long(1), // Required aws.Int64(1), // Required
// More values... // More values...
}, },
} }
resp, err := svc.DeleteLoadBalancerListeners(params) resp, err := svc.DeleteLoadBalancerListeners(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DeleteLoadBalancerPolicy() { func ExampleELB_DeleteLoadBalancerPolicy() {
@@ -405,22 +315,14 @@ func ExampleELB_DeleteLoadBalancerPolicy() {
resp, err := svc.DeleteLoadBalancerPolicy(params) resp, err := svc.DeleteLoadBalancerPolicy(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DeregisterInstancesFromLoadBalancer() { func ExampleELB_DeregisterInstancesFromLoadBalancer() {
@@ -428,8 +330,8 @@ func ExampleELB_DeregisterInstancesFromLoadBalancer() {
params := &elb.DeregisterInstancesFromLoadBalancerInput{ params := &elb.DeregisterInstancesFromLoadBalancerInput{
Instances: []*elb.Instance{ // Required Instances: []*elb.Instance{ // Required
&elb.Instance{ // Required { // Required
InstanceID: aws.String("InstanceId"), InstanceId: aws.String("InstanceId"),
}, },
// More values... // More values...
}, },
@@ -438,22 +340,14 @@ func ExampleELB_DeregisterInstancesFromLoadBalancer() {
resp, err := svc.DeregisterInstancesFromLoadBalancer(params) resp, err := svc.DeregisterInstancesFromLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeInstanceHealth() { func ExampleELB_DescribeInstanceHealth() {
@@ -462,8 +356,8 @@ func ExampleELB_DescribeInstanceHealth() {
params := &elb.DescribeInstanceHealthInput{ params := &elb.DescribeInstanceHealthInput{
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
Instances: []*elb.Instance{ Instances: []*elb.Instance{
&elb.Instance{ // Required { // Required
InstanceID: aws.String("InstanceId"), InstanceId: aws.String("InstanceId"),
}, },
// More values... // More values...
}, },
@@ -471,22 +365,14 @@ func ExampleELB_DescribeInstanceHealth() {
resp, err := svc.DescribeInstanceHealth(params) resp, err := svc.DescribeInstanceHealth(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeLoadBalancerAttributes() { func ExampleELB_DescribeLoadBalancerAttributes() {
@@ -498,22 +384,14 @@ func ExampleELB_DescribeLoadBalancerAttributes() {
resp, err := svc.DescribeLoadBalancerAttributes(params) resp, err := svc.DescribeLoadBalancerAttributes(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeLoadBalancerPolicies() { func ExampleELB_DescribeLoadBalancerPolicies() {
@@ -529,22 +407,14 @@ func ExampleELB_DescribeLoadBalancerPolicies() {
resp, err := svc.DescribeLoadBalancerPolicies(params) resp, err := svc.DescribeLoadBalancerPolicies(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeLoadBalancerPolicyTypes() { func ExampleELB_DescribeLoadBalancerPolicyTypes() {
@@ -559,22 +429,14 @@ func ExampleELB_DescribeLoadBalancerPolicyTypes() {
resp, err := svc.DescribeLoadBalancerPolicyTypes(params) resp, err := svc.DescribeLoadBalancerPolicyTypes(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeLoadBalancers() { func ExampleELB_DescribeLoadBalancers() {
@@ -586,27 +448,19 @@ func ExampleELB_DescribeLoadBalancers() {
// More values... // More values...
}, },
Marker: aws.String("Marker"), Marker: aws.String("Marker"),
PageSize: aws.Long(1), PageSize: aws.Int64(1),
} }
resp, err := svc.DescribeLoadBalancers(params) resp, err := svc.DescribeLoadBalancers(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DescribeTags() { func ExampleELB_DescribeTags() {
@@ -621,22 +475,14 @@ func ExampleELB_DescribeTags() {
resp, err := svc.DescribeTags(params) resp, err := svc.DescribeTags(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DetachLoadBalancerFromSubnets() { func ExampleELB_DetachLoadBalancerFromSubnets() {
@@ -652,22 +498,14 @@ func ExampleELB_DetachLoadBalancerFromSubnets() {
resp, err := svc.DetachLoadBalancerFromSubnets(params) resp, err := svc.DetachLoadBalancerFromSubnets(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_DisableAvailabilityZonesForLoadBalancer() { func ExampleELB_DisableAvailabilityZonesForLoadBalancer() {
@@ -683,22 +521,14 @@ func ExampleELB_DisableAvailabilityZonesForLoadBalancer() {
resp, err := svc.DisableAvailabilityZonesForLoadBalancer(params) resp, err := svc.DisableAvailabilityZonesForLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_EnableAvailabilityZonesForLoadBalancer() { func ExampleELB_EnableAvailabilityZonesForLoadBalancer() {
@@ -714,22 +544,14 @@ func ExampleELB_EnableAvailabilityZonesForLoadBalancer() {
resp, err := svc.EnableAvailabilityZonesForLoadBalancer(params) resp, err := svc.EnableAvailabilityZonesForLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_ModifyLoadBalancerAttributes() { func ExampleELB_ModifyLoadBalancerAttributes() {
@@ -738,27 +560,27 @@ func ExampleELB_ModifyLoadBalancerAttributes() {
params := &elb.ModifyLoadBalancerAttributesInput{ params := &elb.ModifyLoadBalancerAttributesInput{
LoadBalancerAttributes: &elb.LoadBalancerAttributes{ // Required LoadBalancerAttributes: &elb.LoadBalancerAttributes{ // Required
AccessLog: &elb.AccessLog{ AccessLog: &elb.AccessLog{
Enabled: aws.Boolean(true), // Required Enabled: aws.Bool(true), // Required
EmitInterval: aws.Long(1), EmitInterval: aws.Int64(1),
S3BucketName: aws.String("S3BucketName"), S3BucketName: aws.String("S3BucketName"),
S3BucketPrefix: aws.String("AccessLogPrefix"), S3BucketPrefix: aws.String("AccessLogPrefix"),
}, },
AdditionalAttributes: []*elb.AdditionalAttribute{ AdditionalAttributes: []*elb.AdditionalAttribute{
&elb.AdditionalAttribute{ // Required { // Required
Key: aws.String("StringVal"), Key: aws.String("StringVal"),
Value: aws.String("StringVal"), Value: aws.String("StringVal"),
}, },
// More values... // More values...
}, },
ConnectionDraining: &elb.ConnectionDraining{ ConnectionDraining: &elb.ConnectionDraining{
Enabled: aws.Boolean(true), // Required Enabled: aws.Bool(true), // Required
Timeout: aws.Long(1), Timeout: aws.Int64(1),
}, },
ConnectionSettings: &elb.ConnectionSettings{ ConnectionSettings: &elb.ConnectionSettings{
IdleTimeout: aws.Long(1), // Required IdleTimeout: aws.Int64(1), // Required
}, },
CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{ CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{
Enabled: aws.Boolean(true), // Required Enabled: aws.Bool(true), // Required
}, },
}, },
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
@@ -766,22 +588,14 @@ func ExampleELB_ModifyLoadBalancerAttributes() {
resp, err := svc.ModifyLoadBalancerAttributes(params) resp, err := svc.ModifyLoadBalancerAttributes(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_RegisterInstancesWithLoadBalancer() { func ExampleELB_RegisterInstancesWithLoadBalancer() {
@@ -789,8 +603,8 @@ func ExampleELB_RegisterInstancesWithLoadBalancer() {
params := &elb.RegisterInstancesWithLoadBalancerInput{ params := &elb.RegisterInstancesWithLoadBalancerInput{
Instances: []*elb.Instance{ // Required Instances: []*elb.Instance{ // Required
&elb.Instance{ // Required { // Required
InstanceID: aws.String("InstanceId"), InstanceId: aws.String("InstanceId"),
}, },
// More values... // More values...
}, },
@@ -799,22 +613,14 @@ func ExampleELB_RegisterInstancesWithLoadBalancer() {
resp, err := svc.RegisterInstancesWithLoadBalancer(params) resp, err := svc.RegisterInstancesWithLoadBalancer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_RemoveTags() { func ExampleELB_RemoveTags() {
@@ -826,7 +632,7 @@ func ExampleELB_RemoveTags() {
// More values... // More values...
}, },
Tags: []*elb.TagKeyOnly{ // Required Tags: []*elb.TagKeyOnly{ // Required
&elb.TagKeyOnly{ // Required { // Required
Key: aws.String("TagKey"), Key: aws.String("TagKey"),
}, },
// More values... // More values...
@@ -835,22 +641,14 @@ func ExampleELB_RemoveTags() {
resp, err := svc.RemoveTags(params) resp, err := svc.RemoveTags(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_SetLoadBalancerListenerSSLCertificate() { func ExampleELB_SetLoadBalancerListenerSSLCertificate() {
@@ -858,35 +656,27 @@ func ExampleELB_SetLoadBalancerListenerSSLCertificate() {
params := &elb.SetLoadBalancerListenerSSLCertificateInput{ params := &elb.SetLoadBalancerListenerSSLCertificateInput{
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
LoadBalancerPort: aws.Long(1), // Required LoadBalancerPort: aws.Int64(1), // Required
SSLCertificateID: aws.String("SSLCertificateId"), // Required SSLCertificateId: aws.String("SSLCertificateId"), // Required
} }
resp, err := svc.SetLoadBalancerListenerSSLCertificate(params) resp, err := svc.SetLoadBalancerListenerSSLCertificate(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_SetLoadBalancerPoliciesForBackendServer() { func ExampleELB_SetLoadBalancerPoliciesForBackendServer() {
svc := elb.New(nil) svc := elb.New(nil)
params := &elb.SetLoadBalancerPoliciesForBackendServerInput{ params := &elb.SetLoadBalancerPoliciesForBackendServerInput{
InstancePort: aws.Long(1), // Required InstancePort: aws.Int64(1), // Required
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
PolicyNames: []*string{ // Required PolicyNames: []*string{ // Required
aws.String("PolicyName"), // Required aws.String("PolicyName"), // Required
@@ -896,22 +686,14 @@ func ExampleELB_SetLoadBalancerPoliciesForBackendServer() {
resp, err := svc.SetLoadBalancerPoliciesForBackendServer(params) resp, err := svc.SetLoadBalancerPoliciesForBackendServer(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }
func ExampleELB_SetLoadBalancerPoliciesOfListener() { func ExampleELB_SetLoadBalancerPoliciesOfListener() {
@@ -919,7 +701,7 @@ func ExampleELB_SetLoadBalancerPoliciesOfListener() {
params := &elb.SetLoadBalancerPoliciesOfListenerInput{ params := &elb.SetLoadBalancerPoliciesOfListenerInput{
LoadBalancerName: aws.String("AccessPointName"), // Required LoadBalancerName: aws.String("AccessPointName"), // Required
LoadBalancerPort: aws.Long(1), // Required LoadBalancerPort: aws.Int64(1), // Required
PolicyNames: []*string{ // Required PolicyNames: []*string{ // Required
aws.String("PolicyName"), // Required aws.String("PolicyName"), // Required
// More values... // More values...
@@ -928,20 +710,12 @@ func ExampleELB_SetLoadBalancerPoliciesOfListener() {
resp, err := svc.SetLoadBalancerPoliciesOfListener(params) resp, err := svc.SetLoadBalancerPoliciesOfListener(params)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok { // Print the error, cast err to awserr.Error to get the Code and
// Generic AWS Error with Code, Message, and original error (if any) // Message from an error.
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
}
} else {
// This case should never be hit, The SDK should alwsy return an
// error which satisfies the awserr.Error interface.
fmt.Println(err.Error()) fmt.Println(err.Error())
} return
} }
// Pretty-print the response data. // Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp)) fmt.Println(resp)
} }

View File

@@ -4,27 +4,45 @@ package elb
import ( import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/service"
"github.com/aws/aws-sdk-go/aws/service/serviceinfo"
"github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/query"
"github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/signer/v4"
) )
// ELB is a client for Elastic Load Balancing. // Elastic Load Balancing distributes incoming traffic across your EC2 instances.
//
// For information about the features of Elastic Load Balancing, see What Is
// Elastic Load Balancing? (http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elastic-load-balancing.html)
// in the Elastic Load Balancing Developer Guide.
//
// For information about the AWS regions supported by Elastic Load Balancing,
// see Regions and Endpoints - Elastic Load Balancing (http://docs.aws.amazon.com/general/latest/gr/rande.html#elb_region)
// in the Amazon Web Services General Reference.
//
// All Elastic Load Balancing operations are idempotent, which means that they
// complete at most one time. If you repeat an operation, it succeeds with a
// 200 OK response code.
type ELB struct { type ELB struct {
*aws.Service *service.Service
} }
// Used for custom service initialization logic // Used for custom service initialization logic
var initService func(*aws.Service) var initService func(*service.Service)
// Used for custom request initialization logic // Used for custom request initialization logic
var initRequest func(*aws.Request) var initRequest func(*request.Request)
// New returns a new ELB client. // New returns a new ELB client.
func New(config *aws.Config) *ELB { func New(config *aws.Config) *ELB {
service := &aws.Service{ service := &service.Service{
Config: aws.DefaultConfig.Merge(config), ServiceInfo: serviceinfo.ServiceInfo{
Config: defaults.DefaultConfig.Merge(config),
ServiceName: "elasticloadbalancing", ServiceName: "elasticloadbalancing",
APIVersion: "2012-06-01", APIVersion: "2012-06-01",
},
} }
service.Initialize() service.Initialize()
@@ -45,8 +63,8 @@ func New(config *aws.Config) *ELB {
// newRequest creates a new request for a ELB operation and runs any // newRequest creates a new request for a ELB operation and runs any
// custom request initialization. // custom request initialization.
func (c *ELB) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { func (c *ELB) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := aws.NewRequest(c.Service, op, params, data) req := c.NewRequest(op, params, data)
// Run custom request initialization if present // Run custom request initialization if present
if initRequest != nil { if initRequest != nil {