Update to latest aws and move off of hashicorp/aws-sdk-go

This commit is contained in:
Seth Vargo 2015-08-06 12:26:41 -04:00
parent 139398c61e
commit 070d45456a
69 changed files with 3513 additions and 5775 deletions

47
Godeps/Godeps.json generated
View file

@ -12,43 +12,43 @@
},
{
"ImportPath": "github.com/aws/aws-sdk-go/aws",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/endpoints",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/query",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/rest",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/restxml",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/internal/signer/v4",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/aws/aws-sdk-go/service/s3",
"Comment": "v0.6.4-5-g127313c",
"Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d"
"Comment": "v0.7.2-4-g5df83ba",
"Rev": "5df83ba895b6ba073c0513dddcec6d7473c95592"
},
{
"ImportPath": "github.com/coreos/go-etcd/etcd",
@ -94,21 +94,6 @@
"ImportPath": "github.com/google/go-querystring/query",
"Rev": "547ef5ac979778feb2f760cdb5f4eae1a2207b86"
},
{
"ImportPath": "github.com/hashicorp/aws-sdk-go/aws",
"Comment": "tf0.4.0-3-ge6ea019",
"Rev": "e6ea0192eee4640f32ec73c0cbb71f63e4f2b65a"
},
{
"ImportPath": "github.com/hashicorp/aws-sdk-go/gen/endpoints",
"Comment": "tf0.4.0-3-ge6ea019",
"Rev": "e6ea0192eee4640f32ec73c0cbb71f63e4f2b65a"
},
{
"ImportPath": "github.com/hashicorp/aws-sdk-go/gen/iam",
"Comment": "tf0.4.0-3-ge6ea019",
"Rev": "e6ea0192eee4640f32ec73c0cbb71f63e4f2b65a"
},
{
"ImportPath": "github.com/hashicorp/consul/api",
"Comment": "v0.5.2-144-g2783f2b",

View file

@ -10,23 +10,23 @@ package awserr
//
// Example:
//
// output, err := s3manage.Upload(svc, input, opts)
// if err != nil {
// if awsErr, ok := err.(awserr.Error); ok {
// // Get error details
// log.Println("Error:", err.Code(), err.Message())
// output, err := s3manage.Upload(svc, input, opts)
// if err != nil {
// if awsErr, ok := err.(awserr.Error); ok {
// // Get error details
// log.Println("Error:", err.Code(), err.Message())
//
// Prints out full error message, including original error if there was one.
// log.Println("Error:", err.Error())
// // Prints out full error message, including original error if there was one.
// log.Println("Error:", err.Error())
//
// // Get original error
// if origErr := err.Err(); origErr != nil {
// // operate on original error.
// }
// } else {
// fmt.Println(err.Error())
// }
// }
// // Get original error
// if origErr := err.Err(); origErr != nil {
// // operate on original error.
// }
// } else {
// fmt.Println(err.Error())
// }
// }
//
type Error interface {
// Satisfy the generic error interface.

View file

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

View file

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

View file

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

View file

@ -44,6 +44,7 @@ func TestValueAtPathFailure(t *testing.T) {
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{}{}, awsutil.ValuesAtPath(nil, "A.B.C"))
assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(Struct{}, "A"))
}
func TestSetValueAtPathSuccess(t *testing.T) {
@ -62,4 +63,6 @@ func TestSetValueAtPathSuccess(t *testing.T) {
var s2 Struct
awsutil.SetValueAtAnyPath(&s2, "b.b.c", "test0")
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"
)
// StringValue returns the string representation of a value.
func StringValue(i interface{}) string {
// Prettify returns the string representation of a value.
func Prettify(i interface{}) string {
var buf bytes.Buffer
stringValue(reflect.ValueOf(i), 0, &buf)
prettify(reflect.ValueOf(i), 0, &buf)
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.
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 {
v = v.Elem()
}
@ -52,7 +52,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
val := v.FieldByName(n)
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(n + ": ")
stringValue(val, indent+2, buf)
prettify(val, indent+2, buf)
if i < len(names)-1 {
buf.WriteString(",\n")
@ -68,7 +68,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
buf.WriteString("[" + nl)
for i := 0; i < v.Len(); i++ {
buf.WriteString(id2)
stringValue(v.Index(i), indent+2, buf)
prettify(v.Index(i), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString("," + nl)
@ -82,7 +82,7 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
for i, k := range v.MapKeys() {
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(k.String() + ": ")
stringValue(v.MapIndex(k), indent+2, buf)
prettify(v.MapIndex(k), indent+2, buf)
if i < v.Len()-1 {
buf.WriteString(",\n")

View file

@ -1,7 +1,6 @@
package aws
import (
"io"
"net/http"
"os"
"time"
@ -26,148 +25,230 @@ var DefaultChainCredentials = credentials.NewChainCredentials(
const DefaultRetries = -1
// DefaultConfig is the default all service configuration will be based off of.
var DefaultConfig = &Config{
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,
}
// 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 = NewConfig().
WithCredentials(DefaultChainCredentials).
WithRegion(os.Getenv("AWS_REGION")).
WithHTTPClient(http.DefaultClient).
WithMaxRetries(DefaultRetries).
WithLogger(NewDefaultLogger()).
WithLogLevel(LogOff)
// A Config provides service configuration
// A Config provides service configuration for service clients. By default,
// all clients will use the {DefaultConfig} structure.
type Config struct {
Credentials *credentials.Credentials
Endpoint string
Region string
DisableSSL bool
ManualSend bool
HTTPClient *http.Client
LogHTTPBody bool
LogLevel uint
Logger io.Writer
MaxRetries int
DisableParamValidation bool
DisableComputeChecksums bool
S3ForcePathStyle bool
// The credentials object to use when signing requests. Defaults to
// {DefaultChainCredentials}.
Credentials *credentials.Credentials
// An optional endpoint URL (hostname only or fully qualified URI)
// that overrides the default generated endpoint for a client. Set this
// 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
// 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.
LogLevel *LogLevelType
// 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
}
// Copy will return a shallow copy of the Config object.
func (c Config) Copy() Config {
dst := Config{}
dst.Credentials = c.Credentials
dst.Endpoint = c.Endpoint
dst.Region = c.Region
dst.DisableSSL = c.DisableSSL
dst.ManualSend = c.ManualSend
dst.HTTPClient = c.HTTPClient
dst.LogHTTPBody = c.LogHTTPBody
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
// NewConfig returns a new Config pointer that can be chained with builder methods to
// set multiple configuration values inline without using pointers.
//
// svc := s3.New(aws.NewConfig().WithRegion("us-west-2").WithMaxRetries(10))
//
func NewConfig() *Config {
return &Config{}
}
// Merge merges the newcfg attribute values into this Config. Each attribute
// will be merged into this config if the newcfg attribute's value is non-zero.
// Due to this, newcfg attributes with zero values cannot be merged in. For
// example bool attributes cannot be cleared using Merge, and must be explicitly
// set on the Config structure.
func (c Config) Merge(newcfg *Config) *Config {
if newcfg == nil {
// WithCredentials sets a config Credentials value returning a Config pointer
// for chaining.
func (c *Config) WithCredentials(creds *credentials.Credentials) *Config {
c.Credentials = creds
return c
}
// 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
}
// 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
}
cfg := Config{}
dst := c
if newcfg.Credentials != nil {
cfg.Credentials = newcfg.Credentials
} else {
cfg.Credentials = c.Credentials
if other.Credentials != nil {
dst.Credentials = other.Credentials
}
if newcfg.Endpoint != "" {
cfg.Endpoint = newcfg.Endpoint
} else {
cfg.Endpoint = c.Endpoint
if other.Endpoint != nil {
dst.Endpoint = other.Endpoint
}
if newcfg.Region != "" {
cfg.Region = newcfg.Region
} else {
cfg.Region = c.Region
if other.Region != nil {
dst.Region = other.Region
}
if newcfg.DisableSSL {
cfg.DisableSSL = newcfg.DisableSSL
} else {
cfg.DisableSSL = c.DisableSSL
if other.DisableSSL != nil {
dst.DisableSSL = other.DisableSSL
}
if newcfg.ManualSend {
cfg.ManualSend = newcfg.ManualSend
} else {
cfg.ManualSend = c.ManualSend
if other.HTTPClient != nil {
dst.HTTPClient = other.HTTPClient
}
if newcfg.HTTPClient != nil {
cfg.HTTPClient = newcfg.HTTPClient
} else {
cfg.HTTPClient = c.HTTPClient
if other.LogLevel != nil {
dst.LogLevel = other.LogLevel
}
if newcfg.LogHTTPBody {
cfg.LogHTTPBody = newcfg.LogHTTPBody
} else {
cfg.LogHTTPBody = c.LogHTTPBody
if other.Logger != nil {
dst.Logger = other.Logger
}
if newcfg.LogLevel != 0 {
cfg.LogLevel = newcfg.LogLevel
} else {
cfg.LogLevel = c.LogLevel
if other.MaxRetries != nil {
dst.MaxRetries = other.MaxRetries
}
if newcfg.Logger != nil {
cfg.Logger = newcfg.Logger
} else {
cfg.Logger = c.Logger
if other.DisableParamValidation != nil {
dst.DisableParamValidation = other.DisableParamValidation
}
if newcfg.MaxRetries != DefaultRetries {
cfg.MaxRetries = newcfg.MaxRetries
} else {
cfg.MaxRetries = c.MaxRetries
if other.DisableComputeChecksums != nil {
dst.DisableComputeChecksums = other.DisableComputeChecksums
}
if newcfg.DisableParamValidation {
cfg.DisableParamValidation = newcfg.DisableParamValidation
} else {
cfg.DisableParamValidation = c.DisableParamValidation
if other.S3ForcePathStyle != nil {
dst.S3ForcePathStyle = other.S3ForcePathStyle
}
if newcfg.DisableComputeChecksums {
cfg.DisableComputeChecksums = newcfg.DisableComputeChecksums
} else {
cfg.DisableComputeChecksums = c.DisableComputeChecksums
}
if newcfg.S3ForcePathStyle {
cfg.S3ForcePathStyle = newcfg.S3ForcePathStyle
} else {
cfg.S3ForcePathStyle = c.S3ForcePathStyle
}
return &cfg
return &dst
}
// Copy will return a shallow copy of the Config object.
func (c Config) Copy() *Config {
dst := c
return &dst
}

View file

@ -2,7 +2,6 @@ package aws
import (
"net/http"
"os"
"reflect"
"testing"
"time"
@ -20,24 +19,22 @@ var testCredentials = credentials.NewChainCredentials([]credentials.Provider{
var copyTestConfig = Config{
Credentials: testCredentials,
Endpoint: "CopyTestEndpoint",
Region: "COPY_TEST_AWS_REGION",
DisableSSL: true,
ManualSend: true,
Endpoint: String("CopyTestEndpoint"),
Region: String("COPY_TEST_AWS_REGION"),
DisableSSL: Bool(true),
HTTPClient: http.DefaultClient,
LogHTTPBody: true,
LogLevel: 2,
Logger: os.Stdout,
MaxRetries: DefaultRetries,
DisableParamValidation: true,
DisableComputeChecksums: true,
S3ForcePathStyle: true,
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) {
if !reflect.DeepEqual(*got, want) {
t.Errorf("Copy() = %+v", got)
t.Errorf(" want %+v", want)
}
@ -46,27 +43,25 @@ func TestCopy(t *testing.T) {
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)
if got == &want {
t.Errorf("Copy() = %p; want different instance as source %p", got, &want)
}
}
var mergeTestZeroValueConfig = Config{MaxRetries: DefaultRetries}
var mergeTestZeroValueConfig = Config{}
var mergeTestConfig = Config{
Credentials: testCredentials,
Endpoint: "MergeTestEndpoint",
Region: "MERGE_TEST_AWS_REGION",
DisableSSL: true,
ManualSend: true,
Endpoint: String("MergeTestEndpoint"),
Region: String("MERGE_TEST_AWS_REGION"),
DisableSSL: Bool(true),
HTTPClient: http.DefaultClient,
LogHTTPBody: true,
LogLevel: 2,
Logger: os.Stdout,
MaxRetries: 10,
DisableParamValidation: true,
DisableComputeChecksums: true,
S3ForcePathStyle: true,
LogLevel: LogLevel(LogDebug),
Logger: NewDefaultLogger(),
MaxRetries: Int(10),
DisableParamValidation: Bool(true),
DisableComputeChecksums: Bool(true),
S3ForcePathStyle: Bool(true),
}
var mergeTests = []struct {
@ -80,13 +75,13 @@ var mergeTests = []struct {
}
func TestMerge(t *testing.T) {
for _, tt := range mergeTests {
for i, tt := range mergeTests {
got := tt.cfg.Merge(tt.in)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Config %+v", tt.cfg)
t.Errorf(" Merge(%+v)", tt.in)
t.Errorf(" got %+v", got)
t.Errorf(" want %+v", 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,438 @@
package aws_test
import (
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"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 := aws.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 := aws.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{
{aws.String("a"), aws.String("b"), nil, aws.String("c")},
}
func TestStringValueSlice(t *testing.T) {
for idx, in := range testCasesStringValueSlice {
if in == nil {
continue
}
out := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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 := aws.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

@ -7,6 +7,8 @@ import (
var (
// ErrNoValidProvidersFoundInChain Is returned when there are no valid
// providers in the ChainProvider.
//
// @readonly
ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", "no valid providers in chain", nil)
)

View file

@ -63,6 +63,7 @@ import (
// svc := s3.New(&aws.Config{Credentials: AnonymousCredentials})
// // Access public S3 buckets.
//
// @readonly
var AnonymousCredentials = NewStaticCredentials("", "", "")
// A Value is the AWS credentials value for individual credential fields.

View file

@ -31,7 +31,6 @@ const metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam
// // specified the credentials will be expired early
// ExpiryWindow: 0,
// }
//
type EC2RoleProvider struct {
Expiry

View file

@ -9,9 +9,14 @@ import (
var (
// ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
// found in the process's environment.
//
// @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
// can't be found in the process's environment.
//
// @readonly
ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil)
)
@ -19,8 +24,9 @@ var (
// running process. Environment credentials never expire.
//
// 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 {
retrieved bool
}

View file

@ -12,6 +12,8 @@ import (
var (
// ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found.
//
// @readonly
ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil)
)

View file

@ -6,6 +6,8 @@ import (
var (
// ErrStaticCredentialsEmpty is emitted when static credentials are empty.
//
// @readonly
ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil)
)

View file

@ -100,7 +100,7 @@ func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {
}
roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{
DurationSeconds: aws.Long(int64(p.Duration / time.Second)),
DurationSeconds: aws.Int64(int64(p.Duration / time.Second)),
RoleARN: aws.String(p.RoleARN),
RoleSessionName: aws.String(p.RoleSessionName),
})

View file

@ -90,7 +90,7 @@ func SendHandler(r *Request) {
}
// Catch all other request errors.
r.Error = awserr.New("RequestError", "send request failed", err)
r.Retryable.Set(true) // network errors are retryable
r.Retryable = Bool(true) // network errors are retryable
}
}
@ -107,8 +107,8 @@ func ValidateResponseHandler(r *Request) {
func AfterRetryHandler(r *Request) {
// If one of the other handlers already set the retry state
// we don't want to override it based on the service's state
if !r.Retryable.IsSet() {
r.Retryable.Set(r.Service.ShouldRetry(r))
if r.Retryable == nil {
r.Retryable = Bool(r.Service.ShouldRetry(r))
}
if r.WillRetry() {
@ -134,10 +134,14 @@ func AfterRetryHandler(r *Request) {
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)
)
@ -145,7 +149,7 @@ var (
// appropriate Region and Endpoint set. Will set r.Error if the endpoint or
// region is not valid.
func ValidateEndpointHandler(r *Request) {
if r.Service.SigningRegion == "" && r.Service.Config.Region == "" {
if r.Service.SigningRegion == "" && StringValue(r.Service.Config.Region) == "" {
r.Error = ErrMissingRegion
} else if r.Service.Endpoint == "" {
r.Error = ErrMissingEndpoint

View file

@ -12,7 +12,7 @@ import (
func TestValidateEndpointHandler(t *testing.T) {
os.Clearenv()
svc := NewService(&Config{Region: "us-west-2"})
svc := NewService(NewConfig().WithRegion("us-west-2"))
svc.Handlers.Clear()
svc.Handlers.Validate.PushBack(ValidateEndpointHandler)
@ -37,11 +37,11 @@ func TestValidateEndpointHandlerErrorRegion(t *testing.T) {
type mockCredsProvider struct {
expired bool
retreiveCalled bool
retrieveCalled bool
}
func (m *mockCredsProvider) Retrieve() (credentials.Value, error) {
m.retreiveCalled = true
m.retrieveCalled = true
return credentials.Value{}, nil
}
@ -52,7 +52,7 @@ func (m *mockCredsProvider) IsExpired() bool {
func TestAfterRetryRefreshCreds(t *testing.T) {
os.Clearenv()
credProvider := &mockCredsProvider{}
svc := NewService(&Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: 1})
svc := NewService(&Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: Int(1)})
svc.Handlers.Clear()
svc.Handlers.ValidateResponse.PushBack(func(r *Request) {
@ -67,15 +67,15 @@ func TestAfterRetryRefreshCreds(t *testing.T) {
})
assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
assert.False(t, credProvider.retreiveCalled)
assert.False(t, credProvider.retrieveCalled)
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
req.Send()
assert.True(t, svc.Config.Credentials.IsExpired())
assert.False(t, credProvider.retreiveCalled)
assert.False(t, credProvider.retrieveCalled)
_, err := svc.Config.Credentials.Get()
assert.NoError(t, err)
assert.True(t, credProvider.retreiveCalled)
assert.True(t, credProvider.retrieveCalled)
}

View file

@ -23,7 +23,7 @@ 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.PushFront(func(r *Request) { r.Data = Bool(true) })
l.Run(r)
if r.Data != nil {
t.Error("Expected handler to execute")

View file

@ -0,0 +1,89 @@
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
)
// 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

@ -44,7 +44,7 @@ func TestNoErrors(t *testing.T) {
"key1": {Name: aws.String("Name")},
"key2": {Name: aws.String("Name")},
},
RequiredBool: aws.Boolean(true),
RequiredBool: aws.Bool(true),
OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
}
@ -70,7 +70,7 @@ func TestNestedMissingRequiredParameters(t *testing.T) {
"key1": {Name: aws.String("Name")},
"key2": {},
},
RequiredBool: aws.Boolean(true),
RequiredBool: aws.Bool(true),
OptionalStruct: &ConditionalStructShape{},
}

View file

@ -29,7 +29,7 @@ type Request struct {
Data interface{}
RequestID string
RetryCount uint
Retryable SettableBool
Retryable *bool
RetryDelay time.Duration
built bool
@ -89,7 +89,7 @@ func NewRequest(service *Service, operation *Operation, params interface{}, data
// WillRetry returns if the request's can be retried.
func (r *Request) WillRetry() bool {
return r.Error != nil && r.Retryable.Get() && r.RetryCount < r.Service.MaxRetries()
return r.Error != nil && BoolValue(r.Retryable) && r.RetryCount < r.Service.MaxRetries()
}
// ParamsFilled returns if the request's parameters have been populated
@ -183,12 +183,12 @@ func (r *Request) Send() error {
return r.Error
}
if r.Retryable.Get() {
if BoolValue(r.Retryable) {
// 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.
r.Body.Seek(r.bodyStart, 0)
}
r.Retryable.Reset()
r.Retryable = nil
r.Handlers.Send.Run(r)
if r.Error != nil {

View file

@ -41,7 +41,7 @@ func TestPagination(t *testing.T) {
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 {
numPages++
for _, t := range p.TableNames {
@ -93,7 +93,7 @@ func TestPaginationEachPage(t *testing.T) {
reqNum++
})
params := &dynamodb.ListTablesInput{Limit: aws.Long(2)}
params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
req, _ := db.ListTablesRequest(params)
err := req.EachPage(func(p interface{}, last bool) bool {
numPages++
@ -138,7 +138,7 @@ func TestPaginationEarlyExit(t *testing.T) {
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 {
numPages++
if numPages == 2 {
@ -189,10 +189,10 @@ func TestPaginationTruncation(t *testing.T) {
reqNum := &count
resps := []*s3.ListObjectsOutput{
{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}},
{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}},
{IsTruncated: aws.Boolean(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}},
{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}},
{IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}},
{IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}},
{IsTruncated: aws.Bool(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}},
{IsTruncated: aws.Bool(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}},
}
client.Handlers.Send.Clear() // mock sending
@ -218,7 +218,7 @@ func TestPaginationTruncation(t *testing.T) {
// Try again without truncation token at all
count = 0
resps[1].IsTruncated = nil
resps[2].IsTruncated = aws.Boolean(true)
resps[2].IsTruncated = aws.Bool(true)
results = []string{}
err = client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool {
results = append(results, *p.Contents[0].Key)
@ -265,7 +265,7 @@ func BenchmarkCodegenIterator(b *testing.B) {
reqNum++
})
input := &dynamodb.ListTablesInput{Limit: aws.Long(2)}
input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error {
page, _ := db.ListTablesRequest(input)
for ; page != nil; page = page.NextPage() {
@ -294,7 +294,7 @@ func BenchmarkEachPageIterator(b *testing.B) {
reqNum++
})
input := &dynamodb.ListTablesInput{Limit: aws.Long(2)}
input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
for i := 0; i < b.N; i++ {
reqNum = 0
req, _ := db.ListTablesRequest(input)

View file

@ -7,7 +7,6 @@ import (
"io"
"io/ioutil"
"net/http"
"reflect"
"testing"
"time"
@ -72,7 +71,7 @@ func TestRequestRecoverRetry5xx(t *testing.T) {
{StatusCode: 200, Body: body(`{"data":"valid"}`)},
}
s := NewService(&Config{MaxRetries: 10})
s := NewService(NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError)
@ -98,7 +97,7 @@ func TestRequestRecoverRetry4xxRetryable(t *testing.T) {
{StatusCode: 200, Body: body(`{"data":"valid"}`)},
}
s := NewService(&Config{MaxRetries: 10})
s := NewService(NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError)
@ -117,7 +116,7 @@ func TestRequestRecoverRetry4xxRetryable(t *testing.T) {
// test that retries don't occur for 4xx status codes with a response type that can't be retried
func TestRequest4xxUnretryable(t *testing.T) {
s := NewService(&Config{MaxRetries: 10})
s := NewService(NewConfig().WithMaxRetries(10))
s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError)
@ -153,7 +152,7 @@ func TestRequestExhaustRetries(t *testing.T) {
{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)},
}
s := NewService(&Config{MaxRetries: -1})
s := NewService(NewConfig().WithMaxRetries(DefaultRetries))
s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError)
@ -173,7 +172,14 @@ func TestRequestExhaustRetries(t *testing.T) {
assert.Equal(t, "UnknownError", err.(awserr.Error).Code())
assert.Equal(t, "An error occurred.", err.(awserr.Error).Message())
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.
@ -184,7 +190,7 @@ func TestRequestRecoverExpiredCreds(t *testing.T) {
{StatusCode: 200, Body: body(`{"data":"valid"}`)},
}
s := NewService(&Config{MaxRetries: 10, Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")})
s := NewService(&Config{MaxRetries: Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")})
s.Handlers.Validate.Clear()
s.Handlers.Unmarshal.PushBack(unmarshal)
s.Handlers.UnmarshalError.PushBack(unmarshalError)

View file

@ -3,6 +3,7 @@ package aws
import (
"fmt"
"math"
"math/rand"
"net/http"
"net/http/httputil"
"regexp"
@ -17,7 +18,6 @@ import (
type Service struct {
Config *Config
Handlers Handlers
ManualSend bool
ServiceName string
APIVersion string
Endpoint string
@ -66,23 +66,23 @@ func (s *Service) Initialize() {
s.AddDebugHandlers()
s.buildEndpoint()
if !s.Config.DisableParamValidation {
if !BoolValue(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
if StringValue(s.Config.Endpoint) != "" {
s.Endpoint = *s.Config.Endpoint
} else {
s.Endpoint, s.SigningRegion =
endpoints.EndpointForRegion(s.ServiceName, s.Config.Region)
endpoints.EndpointForRegion(s.ServiceName, StringValue(s.Config.Region))
}
if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) {
scheme := "https"
if s.Config.DisableSSL {
if BoolValue(s.Config.DisableSSL) {
scheme = "http"
}
s.Endpoint = scheme + "://" + s.Endpoint
@ -92,45 +92,59 @@ func (s *Service) buildEndpoint() {
// 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 {
if !s.Config.LogLevel.AtLeast(LogDebug) {
return
}
s.Handlers.Send.PushFront(func(r *Request) {
logBody := r.Config.LogHTTPBody
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody)
s.Handlers.Send.PushFront(logRequest)
s.Handlers.Send.PushBack(logResponse)
}
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")
})
const logReqMsg = `DEBUG: Request %s/%s Details:
---[ REQUEST POST-SIGN ]-----------------------------
%s
-----------------------------------------------------`
func logRequest(r *Request) {
logBody := r.Config.LogLevel.Matches(LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, logBody)
r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ServiceName, r.Operation.Name, string(dumpedBody)))
}
const logRespMsg = `DEBUG: Response %s/%s Details:
---[ RESPONSE ]--------------------------------------
%s
-----------------------------------------------------`
func logResponse(r *Request) {
var msg = "no reponse data"
if r.HTTPResponse != nil {
logBody := r.Config.LogLevel.Matches(LogDebugWithHTTPBody)
dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, logBody)
msg = string(dumpedBody)
} else if r.Error != nil {
msg = r.Error.Error()
}
r.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.ServiceName, r.Operation.Name, msg))
}
// 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 {
if IntValue(s.Config.MaxRetries) < 0 {
return s.DefaultMaxRetries
}
return uint(s.Config.MaxRetries)
return uint(IntValue(s.Config.MaxRetries))
}
var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))
// 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
delay := int(math.Pow(2, float64(r.RetryCount))) * (seededRand.Intn(30) + 30)
return time.Duration(delay) * time.Millisecond
}
// retryableCodes is a collection of service response codes which are retry-able
@ -139,6 +153,9 @@ var retryableCodes = map[string]struct{}{
"RequestError": {},
"ProvisionedThroughputExceededException": {},
"Throttling": {},
"ThrottlingException": {},
"RequestLimitExceeded": {},
"RequestThrottled": {},
}
// credsExpiredCodes is a collection of error codes which signify the credentials

View file

@ -1,36 +1,9 @@
package aws
import (
"fmt"
"io"
"time"
)
// 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
func ReadSeekCloser(r io.Reader) ReaderSeekerCloser {
return ReaderSeekerCloser{r}
@ -80,52 +53,3 @@ func (r ReaderSeekerCloser) Close() error {
}
return nil
}
// A SettableBool provides a boolean value which includes the state if
// the value was set or unset. The set state is in addition to the value's
// value(true|false)
type SettableBool struct {
value bool
set bool
}
// SetBool returns a SettableBool with a value set
func SetBool(value bool) SettableBool {
return SettableBool{value: value, set: true}
}
// Get returns the value. Will always be false if the SettableBool was not set.
func (b *SettableBool) Get() bool {
if !b.set {
return false
}
return b.value
}
// Set sets the value and updates the state that the value has been set.
func (b *SettableBool) Set(value bool) {
b.value = value
b.set = true
}
// 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

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

View file

@ -30,7 +30,6 @@ var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
// InputService1ProtocolTest is a client for InputService1ProtocolTest.
type InputService1ProtocolTest struct {
*aws.Service
}
@ -106,7 +105,6 @@ type metadataInputService1TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService2ProtocolTest is a client for InputService2ProtocolTest.
type InputService2ProtocolTest struct {
*aws.Service
}
@ -190,7 +188,6 @@ type metadataInputService2TestShapeStructType struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService3ProtocolTest is a client for InputService3ProtocolTest.
type InputService3ProtocolTest struct {
*aws.Service
}
@ -296,7 +293,6 @@ type metadataInputService3TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService4ProtocolTest is a client for InputService4ProtocolTest.
type InputService4ProtocolTest struct {
*aws.Service
}
@ -404,7 +400,6 @@ type metadataInputService4TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService5ProtocolTest is a client for InputService5ProtocolTest.
type InputService5ProtocolTest struct {
*aws.Service
}
@ -510,7 +505,6 @@ type metadataInputService5TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService6ProtocolTest is a client for InputService6ProtocolTest.
type InputService6ProtocolTest struct {
*aws.Service
}
@ -584,7 +578,6 @@ type metadataInputService6TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService7ProtocolTest is a client for InputService7ProtocolTest.
type InputService7ProtocolTest struct {
*aws.Service
}
@ -658,7 +651,6 @@ type metadataInputService7TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService8ProtocolTest is a client for InputService8ProtocolTest.
type InputService8ProtocolTest struct {
*aws.Service
}
@ -732,7 +724,6 @@ type metadataInputService8TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService9ProtocolTest is a client for InputService9ProtocolTest.
type InputService9ProtocolTest struct {
*aws.Service
}

View file

@ -30,7 +30,6 @@ var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
// OutputService1ProtocolTest is a client for OutputService1ProtocolTest.
type OutputService1ProtocolTest struct {
*aws.Service
}
@ -120,7 +119,6 @@ type metadataOutputService1TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService2ProtocolTest is a client for OutputService2ProtocolTest.
type OutputService2ProtocolTest struct {
*aws.Service
}
@ -196,7 +194,6 @@ type metadataOutputService2TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService3ProtocolTest is a client for OutputService3ProtocolTest.
type OutputService3ProtocolTest struct {
*aws.Service
}
@ -270,7 +267,6 @@ type metadataOutputService3TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService4ProtocolTest is a client for OutputService4ProtocolTest.
type OutputService4ProtocolTest struct {
*aws.Service
}
@ -344,7 +340,6 @@ type metadataOutputService4TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService5ProtocolTest is a client for OutputService5ProtocolTest.
type OutputService5ProtocolTest struct {
*aws.Service
}
@ -418,7 +413,6 @@ type metadataOutputService5TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService6ProtocolTest is a client for OutputService6ProtocolTest.
type OutputService6ProtocolTest struct {
*aws.Service
}
@ -492,7 +486,6 @@ type metadataOutputService6TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService7ProtocolTest is a client for OutputService7ProtocolTest.
type OutputService7ProtocolTest struct {
*aws.Service
}
@ -566,7 +559,6 @@ type metadataOutputService7TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService8ProtocolTest is a client for OutputService8ProtocolTest.
type OutputService8ProtocolTest struct {
*aws.Service
}
@ -654,7 +646,6 @@ type metadataOutputService8TestShapeStructureShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService9ProtocolTest is a client for OutputService9ProtocolTest.
type OutputService9ProtocolTest struct {
*aws.Service
}
@ -742,7 +733,6 @@ type metadataOutputService9TestShapeStructureShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService10ProtocolTest is a client for OutputService10ProtocolTest.
type OutputService10ProtocolTest struct {
*aws.Service
}
@ -816,7 +806,6 @@ type metadataOutputService10TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService11ProtocolTest is a client for OutputService11ProtocolTest.
type OutputService11ProtocolTest struct {
*aws.Service
}
@ -900,7 +889,6 @@ type metadataOutputService11TestShapeStructType struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService12ProtocolTest is a client for OutputService12ProtocolTest.
type OutputService12ProtocolTest struct {
*aws.Service
}
@ -974,7 +962,6 @@ type metadataOutputService12TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService13ProtocolTest is a client for OutputService13ProtocolTest.
type OutputService13ProtocolTest struct {
*aws.Service
}
@ -1048,7 +1035,6 @@ type metadataOutputService13TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService14ProtocolTest is a client for OutputService14ProtocolTest.
type OutputService14ProtocolTest struct {
*aws.Service
}

View file

@ -156,8 +156,13 @@ func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Va
func updatePath(url *url.URL, urlPath string) {
scheme, query := url.Scheme, url.RawQuery
hasSlash := strings.HasSuffix(urlPath, "/")
// clean up path
urlPath = path.Clean(urlPath)
if hasSlash && !strings.HasSuffix(urlPath, "/") {
urlPath += "/"
}
// get formatted URL minus scheme so we can build this into Opaque
url.Scheme, url.Path, url.RawQuery = "", "", ""

View file

@ -30,7 +30,6 @@ var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
// InputService1ProtocolTest is a client for InputService1ProtocolTest.
type InputService1ProtocolTest struct {
*aws.Service
}
@ -142,7 +141,6 @@ type metadataInputService1TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService2ProtocolTest is a client for InputService2ProtocolTest.
type InputService2ProtocolTest struct {
*aws.Service
}
@ -224,7 +222,6 @@ type metadataInputService2TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService3ProtocolTest is a client for InputService3ProtocolTest.
type InputService3ProtocolTest struct {
*aws.Service
}
@ -314,7 +311,6 @@ type metadataInputService3TestShapeSubStructure struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService4ProtocolTest is a client for InputService4ProtocolTest.
type InputService4ProtocolTest struct {
*aws.Service
}
@ -404,7 +400,6 @@ type metadataInputService4TestShapeSubStructure struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService5ProtocolTest is a client for InputService5ProtocolTest.
type InputService5ProtocolTest struct {
*aws.Service
}
@ -480,7 +475,6 @@ type metadataInputService5TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService6ProtocolTest is a client for InputService6ProtocolTest.
type InputService6ProtocolTest struct {
*aws.Service
}
@ -556,7 +550,6 @@ type metadataInputService6TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService7ProtocolTest is a client for InputService7ProtocolTest.
type InputService7ProtocolTest struct {
*aws.Service
}
@ -632,7 +625,6 @@ type metadataInputService7TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService8ProtocolTest is a client for InputService8ProtocolTest.
type InputService8ProtocolTest struct {
*aws.Service
}
@ -708,7 +700,6 @@ type metadataInputService8TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService9ProtocolTest is a client for InputService9ProtocolTest.
type InputService9ProtocolTest struct {
*aws.Service
}
@ -794,7 +785,6 @@ type metadataInputService9TestShapeSingleFieldStruct struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService10ProtocolTest is a client for InputService10ProtocolTest.
type InputService10ProtocolTest struct {
*aws.Service
}
@ -882,7 +872,6 @@ type metadataInputService10TestShapeStructureShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService11ProtocolTest is a client for InputService11ProtocolTest.
type InputService11ProtocolTest struct {
*aws.Service
}
@ -958,7 +947,6 @@ type metadataInputService11TestShapeInputShape struct {
SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"`
}
// InputService12ProtocolTest is a client for InputService12ProtocolTest.
type InputService12ProtocolTest struct {
*aws.Service
}
@ -1034,7 +1022,6 @@ type metadataInputService12TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure" payload:"Foo"`
}
// InputService13ProtocolTest is a client for InputService13ProtocolTest.
type InputService13ProtocolTest struct {
*aws.Service
}
@ -1144,7 +1131,6 @@ type metadataInputService13TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure" payload:"Foo"`
}
// InputService14ProtocolTest is a client for InputService14ProtocolTest.
type InputService14ProtocolTest struct {
*aws.Service
}
@ -1298,7 +1284,6 @@ type metadataInputService14TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure" payload:"Foo"`
}
// InputService15ProtocolTest is a client for InputService15ProtocolTest.
type InputService15ProtocolTest struct {
*aws.Service
}
@ -1396,7 +1381,6 @@ type metadataInputService15TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure" payload:"Grant"`
}
// InputService16ProtocolTest is a client for InputService16ProtocolTest.
type InputService16ProtocolTest struct {
*aws.Service
}
@ -1474,7 +1458,6 @@ type metadataInputService16TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService17ProtocolTest is a client for InputService17ProtocolTest.
type InputService17ProtocolTest struct {
*aws.Service
}
@ -1584,7 +1567,6 @@ type metadataInputService17TestShapeInputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService18ProtocolTest is a client for InputService18ProtocolTest.
type InputService18ProtocolTest struct {
*aws.Service
}
@ -1846,7 +1828,6 @@ type metadataInputService18TestShapeRecursiveStructType struct {
SDKShapeTraits bool `type:"structure"`
}
// InputService19ProtocolTest is a client for InputService19ProtocolTest.
type InputService19ProtocolTest struct {
*aws.Service
}
@ -1985,10 +1966,10 @@ func TestInputService2ProtocolTestSerializeOtherScalarTypesCase1(t *testing.T) {
svc.Endpoint = "https://test"
input := &InputService2TestShapeInputShape{
First: aws.Boolean(true),
Fourth: aws.Long(3),
Second: aws.Boolean(false),
Third: aws.Double(1.2),
First: aws.Bool(true),
Fourth: aws.Int64(3),
Second: aws.Bool(false),
Third: aws.Float64(1.2),
}
req, _ := svc.InputService2TestCaseOperation1Request(input)
r := req.HTTPRequest

View file

@ -30,7 +30,6 @@ var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
// OutputService1ProtocolTest is a client for OutputService1ProtocolTest.
type OutputService1ProtocolTest struct {
*aws.Service
}
@ -156,7 +155,6 @@ type metadataOutputService1TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService2ProtocolTest is a client for OutputService2ProtocolTest.
type OutputService2ProtocolTest struct {
*aws.Service
}
@ -230,7 +228,6 @@ type metadataOutputService2TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService3ProtocolTest is a client for OutputService3ProtocolTest.
type OutputService3ProtocolTest struct {
*aws.Service
}
@ -304,7 +301,6 @@ type metadataOutputService3TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService4ProtocolTest is a client for OutputService4ProtocolTest.
type OutputService4ProtocolTest struct {
*aws.Service
}
@ -378,7 +374,6 @@ type metadataOutputService4TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService5ProtocolTest is a client for OutputService5ProtocolTest.
type OutputService5ProtocolTest struct {
*aws.Service
}
@ -452,7 +447,6 @@ type metadataOutputService5TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService6ProtocolTest is a client for OutputService6ProtocolTest.
type OutputService6ProtocolTest struct {
*aws.Service
}
@ -536,7 +530,6 @@ type metadataOutputService6TestShapeSingleStructure struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService7ProtocolTest is a client for OutputService7ProtocolTest.
type OutputService7ProtocolTest struct {
*aws.Service
}
@ -610,7 +603,6 @@ type metadataOutputService7TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService8ProtocolTest is a client for OutputService8ProtocolTest.
type OutputService8ProtocolTest struct {
*aws.Service
}
@ -684,7 +676,6 @@ type metadataOutputService8TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService9ProtocolTest is a client for OutputService9ProtocolTest.
type OutputService9ProtocolTest struct {
*aws.Service
}
@ -770,7 +761,6 @@ type metadataOutputService9TestShapeSingleStructure struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService10ProtocolTest is a client for OutputService10ProtocolTest.
type OutputService10ProtocolTest struct {
*aws.Service
}
@ -844,7 +834,6 @@ type metadataOutputService10TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure" payload:"Stream"`
}
// OutputService11ProtocolTest is a client for OutputService11ProtocolTest.
type OutputService11ProtocolTest struct {
*aws.Service
}
@ -934,7 +923,6 @@ type metadataOutputService11TestShapeOutputShape struct {
SDKShapeTraits bool `type:"structure"`
}
// OutputService12ProtocolTest is a client for OutputService12ProtocolTest.
type OutputService12ProtocolTest struct {
*aws.Service
}

View file

@ -14,10 +14,9 @@ import (
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/internal/protocol/rest"
"github.com/aws/aws-sdk-go/aws"
)
const (
@ -43,8 +42,8 @@ type signer struct {
Credentials *credentials.Credentials
Query url.Values
Body io.ReadSeeker
Debug uint
Logger io.Writer
Debug aws.LogLevelType
Logger aws.Logger
isPresign bool
formattedTime string
@ -73,7 +72,7 @@ func Sign(req *aws.Request) {
region := req.Service.SigningRegion
if region == "" {
region = req.Service.Config.Region
region = aws.StringValue(req.Service.Config.Region)
}
name := req.Service.SigningName
@ -90,7 +89,7 @@ func Sign(req *aws.Request) {
ServiceName: name,
Region: region,
Credentials: req.Service.Config.Credentials,
Debug: req.Service.Config.LogLevel,
Debug: req.Service.Config.LogLevel.Value(),
Logger: req.Service.Config.Logger,
}
@ -138,28 +137,33 @@ func (v4 *signer) sign() error {
v4.build()
if v4.Debug > 0 {
if v4.Debug.Matches(aws.LogDebugWithSigning) {
v4.logSigningInfo()
}
return nil
}
const logSignInfoMsg = `DEBUG: Request Signiture:
---[ CANONICAL STRING ]-----------------------------
%s
---[ STRING TO SIGN ]--------------------------------
%s%s
-----------------------------------------------------`
const logSignedURLMsg = `
---[ SIGNED URL ]------------------------------------
%s`
func (v4 *signer) logSigningInfo() {
out := v4.Logger
fmt.Fprintf(out, "---[ CANONICAL STRING ]-----------------------------\n")
fmt.Fprintln(out, v4.canonicalString)
fmt.Fprintf(out, "---[ STRING TO SIGN ]--------------------------------\n")
fmt.Fprintln(out, v4.stringToSign)
signedURLMsg := ""
if v4.isPresign {
fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n")
fmt.Fprintln(out, v4.Request.URL)
signedURLMsg = fmt.Sprintf(logSignedURLMsg, v4.Request.URL.String())
}
fmt.Fprintf(out, "-----------------------------------------------------\n")
msg := fmt.Sprintf(logSignInfoMsg, v4.canonicalString, v4.stringToSign, signedURLMsg)
v4.Logger.Log(msg)
}
func (v4 *signer) build() {
v4.buildTime() // no depends
v4.buildCredentialString() // no depends
if v4.isPresign {

View file

@ -143,7 +143,7 @@ func TestIgnoreResignRequestWithValidCreds(t *testing.T) {
r := aws.NewRequest(
aws.NewService(&aws.Config{
Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"),
Region: "us-west-2",
Region: aws.String("us-west-2"),
}),
&aws.Operation{
Name: "BatchGetItem",
@ -165,7 +165,7 @@ func TestIgnorePreResignRequestWithValidCreds(t *testing.T) {
r := aws.NewRequest(
aws.NewService(&aws.Config{
Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"),
Region: "us-west-2",
Region: aws.String("us-west-2"),
}),
&aws.Operation{
Name: "BatchGetItem",

File diff suppressed because it is too large Load diff

View file

@ -29,13 +29,13 @@ func buildGetBucketLocation(r *aws.Request) {
}
func populateLocationConstraint(r *aws.Request) {
if r.ParamsFilled() && r.Config.Region != "us-east-1" {
if r.ParamsFilled() && aws.StringValue(r.Config.Region) != "us-east-1" {
in := r.Params.(*CreateBucketInput)
if in.CreateBucketConfiguration == nil {
r.Params = awsutil.CopyOf(r.Params)
in = r.Params.(*CreateBucketInput)
in.CreateBucketConfiguration = &CreateBucketConfiguration{
LocationConstraint: &r.Config.Region,
LocationConstraint: r.Config.Region,
}
}
}

View file

@ -65,7 +65,7 @@ func TestNoPopulateLocationConstraintIfProvided(t *testing.T) {
}
func TestNoPopulateLocationConstraintIfClassic(t *testing.T) {
s := s3.New(&aws.Config{Region: "us-east-1"})
s := s3.New(&aws.Config{Region: aws.String("us-east-1")})
req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{
Bucket: aws.String("bucket"),
})

View file

@ -29,7 +29,7 @@ func ExampleS3_AbortMultipartUpload() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -43,7 +43,7 @@ func ExampleS3_AbortMultipartUpload() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_CompleteMultipartUpload() {
@ -57,7 +57,7 @@ func ExampleS3_CompleteMultipartUpload() {
Parts: []*s3.CompletedPart{
{ // Required
ETag: aws.String("ETag"),
PartNumber: aws.Long(1),
PartNumber: aws.Int64(1),
},
// More values...
},
@ -68,7 +68,7 @@ func ExampleS3_CompleteMultipartUpload() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -82,7 +82,7 @@ func ExampleS3_CompleteMultipartUpload() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_CopyObject() {
@ -128,7 +128,7 @@ func ExampleS3_CopyObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -142,7 +142,7 @@ func ExampleS3_CopyObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_CreateBucket() {
@ -164,7 +164,7 @@ func ExampleS3_CreateBucket() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -178,7 +178,7 @@ func ExampleS3_CreateBucket() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_CreateMultipartUpload() {
@ -215,7 +215,7 @@ func ExampleS3_CreateMultipartUpload() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -229,7 +229,7 @@ func ExampleS3_CreateMultipartUpload() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucket() {
@ -242,7 +242,7 @@ func ExampleS3_DeleteBucket() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -256,7 +256,7 @@ func ExampleS3_DeleteBucket() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketCORS() {
@ -269,7 +269,7 @@ func ExampleS3_DeleteBucketCORS() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -283,7 +283,7 @@ func ExampleS3_DeleteBucketCORS() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketLifecycle() {
@ -296,7 +296,7 @@ func ExampleS3_DeleteBucketLifecycle() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -310,7 +310,7 @@ func ExampleS3_DeleteBucketLifecycle() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketPolicy() {
@ -323,7 +323,7 @@ func ExampleS3_DeleteBucketPolicy() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -337,7 +337,7 @@ func ExampleS3_DeleteBucketPolicy() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketReplication() {
@ -350,7 +350,7 @@ func ExampleS3_DeleteBucketReplication() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -364,7 +364,7 @@ func ExampleS3_DeleteBucketReplication() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketTagging() {
@ -377,7 +377,7 @@ func ExampleS3_DeleteBucketTagging() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -391,7 +391,7 @@ func ExampleS3_DeleteBucketTagging() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteBucketWebsite() {
@ -404,7 +404,7 @@ func ExampleS3_DeleteBucketWebsite() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -418,7 +418,7 @@ func ExampleS3_DeleteBucketWebsite() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteObject() {
@ -435,7 +435,7 @@ func ExampleS3_DeleteObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -449,7 +449,7 @@ func ExampleS3_DeleteObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_DeleteObjects() {
@ -465,7 +465,7 @@ func ExampleS3_DeleteObjects() {
},
// More values...
},
Quiet: aws.Boolean(true),
Quiet: aws.Bool(true),
},
MFA: aws.String("MFA"),
RequestPayer: aws.String("RequestPayer"),
@ -474,7 +474,7 @@ func ExampleS3_DeleteObjects() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -488,7 +488,7 @@ func ExampleS3_DeleteObjects() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketACL() {
@ -501,7 +501,7 @@ func ExampleS3_GetBucketACL() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -515,7 +515,7 @@ func ExampleS3_GetBucketACL() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketCORS() {
@ -528,7 +528,7 @@ func ExampleS3_GetBucketCORS() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -542,7 +542,7 @@ func ExampleS3_GetBucketCORS() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketLifecycle() {
@ -555,7 +555,7 @@ func ExampleS3_GetBucketLifecycle() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -569,7 +569,7 @@ func ExampleS3_GetBucketLifecycle() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketLocation() {
@ -582,7 +582,7 @@ func ExampleS3_GetBucketLocation() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -596,7 +596,7 @@ func ExampleS3_GetBucketLocation() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketLogging() {
@ -609,7 +609,7 @@ func ExampleS3_GetBucketLogging() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -623,7 +623,7 @@ func ExampleS3_GetBucketLogging() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketNotification() {
@ -636,7 +636,7 @@ func ExampleS3_GetBucketNotification() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -650,7 +650,7 @@ func ExampleS3_GetBucketNotification() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketNotificationConfiguration() {
@ -663,7 +663,7 @@ func ExampleS3_GetBucketNotificationConfiguration() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -677,7 +677,7 @@ func ExampleS3_GetBucketNotificationConfiguration() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketPolicy() {
@ -690,7 +690,7 @@ func ExampleS3_GetBucketPolicy() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -704,7 +704,7 @@ func ExampleS3_GetBucketPolicy() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketReplication() {
@ -717,7 +717,7 @@ func ExampleS3_GetBucketReplication() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -731,7 +731,7 @@ func ExampleS3_GetBucketReplication() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketRequestPayment() {
@ -744,7 +744,7 @@ func ExampleS3_GetBucketRequestPayment() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -758,7 +758,7 @@ func ExampleS3_GetBucketRequestPayment() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketTagging() {
@ -771,7 +771,7 @@ func ExampleS3_GetBucketTagging() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -785,7 +785,7 @@ func ExampleS3_GetBucketTagging() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketVersioning() {
@ -798,7 +798,7 @@ func ExampleS3_GetBucketVersioning() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -812,7 +812,7 @@ func ExampleS3_GetBucketVersioning() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetBucketWebsite() {
@ -825,7 +825,7 @@ func ExampleS3_GetBucketWebsite() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -839,7 +839,7 @@ func ExampleS3_GetBucketWebsite() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetObject() {
@ -869,7 +869,7 @@ func ExampleS3_GetObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -883,7 +883,7 @@ func ExampleS3_GetObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetObjectACL() {
@ -899,7 +899,7 @@ func ExampleS3_GetObjectACL() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -913,7 +913,7 @@ func ExampleS3_GetObjectACL() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_GetObjectTorrent() {
@ -928,7 +928,7 @@ func ExampleS3_GetObjectTorrent() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -942,7 +942,7 @@ func ExampleS3_GetObjectTorrent() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_HeadBucket() {
@ -955,7 +955,7 @@ func ExampleS3_HeadBucket() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -969,7 +969,7 @@ func ExampleS3_HeadBucket() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_HeadObject() {
@ -993,7 +993,7 @@ func ExampleS3_HeadObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1007,7 +1007,7 @@ func ExampleS3_HeadObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_ListBuckets() {
@ -1018,7 +1018,7 @@ func ExampleS3_ListBuckets() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1032,7 +1032,7 @@ func ExampleS3_ListBuckets() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_ListMultipartUploads() {
@ -1043,7 +1043,7 @@ func ExampleS3_ListMultipartUploads() {
Delimiter: aws.String("Delimiter"),
EncodingType: aws.String("EncodingType"),
KeyMarker: aws.String("KeyMarker"),
MaxUploads: aws.Long(1),
MaxUploads: aws.Int64(1),
Prefix: aws.String("Prefix"),
UploadIDMarker: aws.String("UploadIdMarker"),
}
@ -1051,7 +1051,7 @@ func ExampleS3_ListMultipartUploads() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1065,7 +1065,7 @@ func ExampleS3_ListMultipartUploads() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_ListObjectVersions() {
@ -1076,7 +1076,7 @@ func ExampleS3_ListObjectVersions() {
Delimiter: aws.String("Delimiter"),
EncodingType: aws.String("EncodingType"),
KeyMarker: aws.String("KeyMarker"),
MaxKeys: aws.Long(1),
MaxKeys: aws.Int64(1),
Prefix: aws.String("Prefix"),
VersionIDMarker: aws.String("VersionIdMarker"),
}
@ -1084,7 +1084,7 @@ func ExampleS3_ListObjectVersions() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1098,7 +1098,7 @@ func ExampleS3_ListObjectVersions() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_ListObjects() {
@ -1109,14 +1109,14 @@ func ExampleS3_ListObjects() {
Delimiter: aws.String("Delimiter"),
EncodingType: aws.String("EncodingType"),
Marker: aws.String("Marker"),
MaxKeys: aws.Long(1),
MaxKeys: aws.Int64(1),
Prefix: aws.String("Prefix"),
}
resp, err := svc.ListObjects(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1130,7 +1130,7 @@ func ExampleS3_ListObjects() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_ListParts() {
@ -1140,15 +1140,15 @@ func ExampleS3_ListParts() {
Bucket: aws.String("BucketName"), // Required
Key: aws.String("ObjectKey"), // Required
UploadID: aws.String("MultipartUploadId"), // Required
MaxParts: aws.Long(1),
PartNumberMarker: aws.Long(1),
MaxParts: aws.Int64(1),
PartNumberMarker: aws.Int64(1),
RequestPayer: aws.String("RequestPayer"),
}
resp, err := svc.ListParts(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1162,7 +1162,7 @@ func ExampleS3_ListParts() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketACL() {
@ -1200,7 +1200,7 @@ func ExampleS3_PutBucketACL() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1214,7 +1214,7 @@ func ExampleS3_PutBucketACL() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketCORS() {
@ -1241,7 +1241,7 @@ func ExampleS3_PutBucketCORS() {
aws.String("ExposeHeader"), // Required
// More values...
},
MaxAgeSeconds: aws.Long(1),
MaxAgeSeconds: aws.Int64(1),
},
// More values...
},
@ -1251,7 +1251,7 @@ func ExampleS3_PutBucketCORS() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1265,7 +1265,7 @@ func ExampleS3_PutBucketCORS() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketLifecycle() {
@ -1280,19 +1280,19 @@ func ExampleS3_PutBucketLifecycle() {
Status: aws.String("ExpirationStatus"), // Required
Expiration: &s3.LifecycleExpiration{
Date: aws.Time(time.Now()),
Days: aws.Long(1),
Days: aws.Int64(1),
},
ID: aws.String("ID"),
NoncurrentVersionExpiration: &s3.NoncurrentVersionExpiration{
NoncurrentDays: aws.Long(1),
NoncurrentDays: aws.Int64(1),
},
NoncurrentVersionTransition: &s3.NoncurrentVersionTransition{
NoncurrentDays: aws.Long(1),
NoncurrentDays: aws.Int64(1),
StorageClass: aws.String("TransitionStorageClass"),
},
Transition: &s3.Transition{
Date: aws.Time(time.Now()),
Days: aws.Long(1),
Days: aws.Int64(1),
StorageClass: aws.String("TransitionStorageClass"),
},
},
@ -1304,7 +1304,7 @@ func ExampleS3_PutBucketLifecycle() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1318,7 +1318,7 @@ func ExampleS3_PutBucketLifecycle() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketLogging() {
@ -1350,7 +1350,7 @@ func ExampleS3_PutBucketLogging() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1364,7 +1364,7 @@ func ExampleS3_PutBucketLogging() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketNotification() {
@ -1407,7 +1407,7 @@ func ExampleS3_PutBucketNotification() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1421,7 +1421,7 @@ func ExampleS3_PutBucketNotification() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketNotificationConfiguration() {
@ -1469,7 +1469,7 @@ func ExampleS3_PutBucketNotificationConfiguration() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1483,7 +1483,7 @@ func ExampleS3_PutBucketNotificationConfiguration() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketPolicy() {
@ -1497,7 +1497,7 @@ func ExampleS3_PutBucketPolicy() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1511,7 +1511,7 @@ func ExampleS3_PutBucketPolicy() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketReplication() {
@ -1538,7 +1538,7 @@ func ExampleS3_PutBucketReplication() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1552,7 +1552,7 @@ func ExampleS3_PutBucketReplication() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketRequestPayment() {
@ -1568,7 +1568,7 @@ func ExampleS3_PutBucketRequestPayment() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1582,7 +1582,7 @@ func ExampleS3_PutBucketRequestPayment() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketTagging() {
@ -1604,7 +1604,7 @@ func ExampleS3_PutBucketTagging() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1618,7 +1618,7 @@ func ExampleS3_PutBucketTagging() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketVersioning() {
@ -1636,7 +1636,7 @@ func ExampleS3_PutBucketVersioning() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1650,7 +1650,7 @@ func ExampleS3_PutBucketVersioning() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutBucketWebsite() {
@ -1691,7 +1691,7 @@ func ExampleS3_PutBucketWebsite() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1705,7 +1705,7 @@ func ExampleS3_PutBucketWebsite() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutObject() {
@ -1720,7 +1720,7 @@ func ExampleS3_PutObject() {
ContentDisposition: aws.String("ContentDisposition"),
ContentEncoding: aws.String("ContentEncoding"),
ContentLanguage: aws.String("ContentLanguage"),
ContentLength: aws.Long(1),
ContentLength: aws.Int64(1),
ContentType: aws.String("ContentType"),
Expires: aws.Time(time.Now()),
GrantFullControl: aws.String("GrantFullControl"),
@ -1744,7 +1744,7 @@ func ExampleS3_PutObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1758,7 +1758,7 @@ func ExampleS3_PutObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_PutObjectACL() {
@ -1798,7 +1798,7 @@ func ExampleS3_PutObjectACL() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1812,7 +1812,7 @@ func ExampleS3_PutObjectACL() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_RestoreObject() {
@ -1823,7 +1823,7 @@ func ExampleS3_RestoreObject() {
Key: aws.String("ObjectKey"), // Required
RequestPayer: aws.String("RequestPayer"),
RestoreRequest: &s3.RestoreRequest{
Days: aws.Long(1), // Required
Days: aws.Int64(1), // Required
},
VersionID: aws.String("ObjectVersionId"),
}
@ -1831,7 +1831,7 @@ func ExampleS3_RestoreObject() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1845,7 +1845,7 @@ func ExampleS3_RestoreObject() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_UploadPart() {
@ -1854,10 +1854,10 @@ func ExampleS3_UploadPart() {
params := &s3.UploadPartInput{
Bucket: aws.String("BucketName"), // Required
Key: aws.String("ObjectKey"), // Required
PartNumber: aws.Long(1), // Required
PartNumber: aws.Int64(1), // Required
UploadID: aws.String("MultipartUploadId"), // Required
Body: bytes.NewReader([]byte("PAYLOAD")),
ContentLength: aws.Long(1),
ContentLength: aws.Int64(1),
RequestPayer: aws.String("RequestPayer"),
SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"),
SSECustomerKey: aws.String("SSECustomerKey"),
@ -1867,7 +1867,7 @@ func ExampleS3_UploadPart() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1881,7 +1881,7 @@ func ExampleS3_UploadPart() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}
func ExampleS3_UploadPartCopy() {
@ -1891,7 +1891,7 @@ func ExampleS3_UploadPartCopy() {
Bucket: aws.String("BucketName"), // Required
CopySource: aws.String("CopySource"), // Required
Key: aws.String("ObjectKey"), // Required
PartNumber: aws.Long(1), // Required
PartNumber: aws.Int64(1), // Required
UploadID: aws.String("MultipartUploadId"), // Required
CopySourceIfMatch: aws.String("CopySourceIfMatch"),
CopySourceIfModifiedSince: aws.Time(time.Now()),
@ -1910,7 +1910,7 @@ func ExampleS3_UploadPartCopy() {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Generic AWS Error with Code, Message, and original error (if any)
// Generic AWS error with Code, Message, and original error (if any)
fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
if reqErr, ok := err.(awserr.RequestFailure); ok {
// A service error occurred
@ -1924,5 +1924,5 @@ func ExampleS3_UploadPartCopy() {
}
// Pretty-print the response data.
fmt.Println(awsutil.StringValue(resp))
fmt.Println(awsutil.Prettify(resp))
}

View file

@ -23,7 +23,7 @@ func dnsCompatibleBucketName(bucket string) bool {
// the host. This is false if S3ForcePathStyle is explicitly set or if the
// bucket is not DNS compatible.
func hostStyleBucketName(r *aws.Request, bucket string) bool {
if r.Config.S3ForcePathStyle {
if aws.BoolValue(r.Config.S3ForcePathStyle) {
return false
}

View file

@ -51,11 +51,11 @@ func TestHostStyleBucketBuild(t *testing.T) {
}
func TestHostStyleBucketBuildNoSSL(t *testing.T) {
s := s3.New(&aws.Config{DisableSSL: true})
s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)})
runTests(t, s, nosslTests)
}
func TestPathStyleBucketBuild(t *testing.T) {
s := s3.New(&aws.Config{S3ForcePathStyle: true})
s := s3.New(&aws.Config{S3ForcePathStyle: aws.Bool(true)})
runTests(t, s, forcepathTests)
}

View file

@ -4,116 +4,233 @@
package s3iface
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
)
// S3API is the interface type for s3.S3.
type S3API interface {
AbortMultipartUploadRequest(*s3.AbortMultipartUploadInput) (*aws.Request, *s3.AbortMultipartUploadOutput)
AbortMultipartUpload(*s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error)
CompleteMultipartUploadRequest(*s3.CompleteMultipartUploadInput) (*aws.Request, *s3.CompleteMultipartUploadOutput)
CompleteMultipartUpload(*s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error)
CopyObjectRequest(*s3.CopyObjectInput) (*aws.Request, *s3.CopyObjectOutput)
CopyObject(*s3.CopyObjectInput) (*s3.CopyObjectOutput, error)
CreateBucketRequest(*s3.CreateBucketInput) (*aws.Request, *s3.CreateBucketOutput)
CreateBucket(*s3.CreateBucketInput) (*s3.CreateBucketOutput, error)
CreateMultipartUploadRequest(*s3.CreateMultipartUploadInput) (*aws.Request, *s3.CreateMultipartUploadOutput)
CreateMultipartUpload(*s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error)
DeleteBucketRequest(*s3.DeleteBucketInput) (*aws.Request, *s3.DeleteBucketOutput)
DeleteBucket(*s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error)
DeleteBucketCORSRequest(*s3.DeleteBucketCORSInput) (*aws.Request, *s3.DeleteBucketCORSOutput)
DeleteBucketCORS(*s3.DeleteBucketCORSInput) (*s3.DeleteBucketCORSOutput, error)
DeleteBucketLifecycleRequest(*s3.DeleteBucketLifecycleInput) (*aws.Request, *s3.DeleteBucketLifecycleOutput)
DeleteBucketLifecycle(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error)
DeleteBucketPolicyRequest(*s3.DeleteBucketPolicyInput) (*aws.Request, *s3.DeleteBucketPolicyOutput)
DeleteBucketPolicy(*s3.DeleteBucketPolicyInput) (*s3.DeleteBucketPolicyOutput, error)
DeleteBucketReplicationRequest(*s3.DeleteBucketReplicationInput) (*aws.Request, *s3.DeleteBucketReplicationOutput)
DeleteBucketReplication(*s3.DeleteBucketReplicationInput) (*s3.DeleteBucketReplicationOutput, error)
DeleteBucketTaggingRequest(*s3.DeleteBucketTaggingInput) (*aws.Request, *s3.DeleteBucketTaggingOutput)
DeleteBucketTagging(*s3.DeleteBucketTaggingInput) (*s3.DeleteBucketTaggingOutput, error)
DeleteBucketWebsiteRequest(*s3.DeleteBucketWebsiteInput) (*aws.Request, *s3.DeleteBucketWebsiteOutput)
DeleteBucketWebsite(*s3.DeleteBucketWebsiteInput) (*s3.DeleteBucketWebsiteOutput, error)
DeleteObjectRequest(*s3.DeleteObjectInput) (*aws.Request, *s3.DeleteObjectOutput)
DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error)
DeleteObjectsRequest(*s3.DeleteObjectsInput) (*aws.Request, *s3.DeleteObjectsOutput)
DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error)
GetBucketACLRequest(*s3.GetBucketACLInput) (*aws.Request, *s3.GetBucketACLOutput)
GetBucketACL(*s3.GetBucketACLInput) (*s3.GetBucketACLOutput, error)
GetBucketCORSRequest(*s3.GetBucketCORSInput) (*aws.Request, *s3.GetBucketCORSOutput)
GetBucketCORS(*s3.GetBucketCORSInput) (*s3.GetBucketCORSOutput, error)
GetBucketLifecycleRequest(*s3.GetBucketLifecycleInput) (*aws.Request, *s3.GetBucketLifecycleOutput)
GetBucketLifecycle(*s3.GetBucketLifecycleInput) (*s3.GetBucketLifecycleOutput, error)
GetBucketLocationRequest(*s3.GetBucketLocationInput) (*aws.Request, *s3.GetBucketLocationOutput)
GetBucketLocation(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error)
GetBucketLoggingRequest(*s3.GetBucketLoggingInput) (*aws.Request, *s3.GetBucketLoggingOutput)
GetBucketLogging(*s3.GetBucketLoggingInput) (*s3.GetBucketLoggingOutput, error)
GetBucketNotificationRequest(*s3.GetBucketNotificationConfigurationRequest) (*aws.Request, *s3.NotificationConfigurationDeprecated)
GetBucketNotification(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfigurationDeprecated, error)
GetBucketNotificationConfigurationRequest(*s3.GetBucketNotificationConfigurationRequest) (*aws.Request, *s3.NotificationConfiguration)
GetBucketNotificationConfiguration(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfiguration, error)
GetBucketPolicyRequest(*s3.GetBucketPolicyInput) (*aws.Request, *s3.GetBucketPolicyOutput)
GetBucketPolicy(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error)
GetBucketReplicationRequest(*s3.GetBucketReplicationInput) (*aws.Request, *s3.GetBucketReplicationOutput)
GetBucketReplication(*s3.GetBucketReplicationInput) (*s3.GetBucketReplicationOutput, error)
GetBucketRequestPaymentRequest(*s3.GetBucketRequestPaymentInput) (*aws.Request, *s3.GetBucketRequestPaymentOutput)
GetBucketRequestPayment(*s3.GetBucketRequestPaymentInput) (*s3.GetBucketRequestPaymentOutput, error)
GetBucketTaggingRequest(*s3.GetBucketTaggingInput) (*aws.Request, *s3.GetBucketTaggingOutput)
GetBucketTagging(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error)
GetBucketVersioningRequest(*s3.GetBucketVersioningInput) (*aws.Request, *s3.GetBucketVersioningOutput)
GetBucketVersioning(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error)
GetBucketWebsiteRequest(*s3.GetBucketWebsiteInput) (*aws.Request, *s3.GetBucketWebsiteOutput)
GetBucketWebsite(*s3.GetBucketWebsiteInput) (*s3.GetBucketWebsiteOutput, error)
GetObjectRequest(*s3.GetObjectInput) (*aws.Request, *s3.GetObjectOutput)
GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error)
GetObjectACLRequest(*s3.GetObjectACLInput) (*aws.Request, *s3.GetObjectACLOutput)
GetObjectACL(*s3.GetObjectACLInput) (*s3.GetObjectACLOutput, error)
GetObjectTorrentRequest(*s3.GetObjectTorrentInput) (*aws.Request, *s3.GetObjectTorrentOutput)
GetObjectTorrent(*s3.GetObjectTorrentInput) (*s3.GetObjectTorrentOutput, error)
HeadBucketRequest(*s3.HeadBucketInput) (*aws.Request, *s3.HeadBucketOutput)
HeadBucket(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error)
HeadObjectRequest(*s3.HeadObjectInput) (*aws.Request, *s3.HeadObjectOutput)
HeadObject(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error)
ListBucketsRequest(*s3.ListBucketsInput) (*aws.Request, *s3.ListBucketsOutput)
ListBuckets(*s3.ListBucketsInput) (*s3.ListBucketsOutput, error)
ListMultipartUploadsRequest(*s3.ListMultipartUploadsInput) (*aws.Request, *s3.ListMultipartUploadsOutput)
ListMultipartUploads(*s3.ListMultipartUploadsInput) (*s3.ListMultipartUploadsOutput, error)
ListMultipartUploadsPages(*s3.ListMultipartUploadsInput, func(*s3.ListMultipartUploadsOutput, bool) bool) error
ListObjectVersionsRequest(*s3.ListObjectVersionsInput) (*aws.Request, *s3.ListObjectVersionsOutput)
ListObjectVersions(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error)
ListObjectVersionsPages(*s3.ListObjectVersionsInput, func(*s3.ListObjectVersionsOutput, bool) bool) error
ListObjectsRequest(*s3.ListObjectsInput) (*aws.Request, *s3.ListObjectsOutput)
ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error)
ListObjectsPages(*s3.ListObjectsInput, func(*s3.ListObjectsOutput, bool) bool) error
ListPartsRequest(*s3.ListPartsInput) (*aws.Request, *s3.ListPartsOutput)
ListParts(*s3.ListPartsInput) (*s3.ListPartsOutput, error)
ListPartsPages(*s3.ListPartsInput, func(*s3.ListPartsOutput, bool) bool) error
PutBucketACLRequest(*s3.PutBucketACLInput) (*aws.Request, *s3.PutBucketACLOutput)
PutBucketACL(*s3.PutBucketACLInput) (*s3.PutBucketACLOutput, error)
PutBucketCORSRequest(*s3.PutBucketCORSInput) (*aws.Request, *s3.PutBucketCORSOutput)
PutBucketCORS(*s3.PutBucketCORSInput) (*s3.PutBucketCORSOutput, error)
PutBucketLifecycleRequest(*s3.PutBucketLifecycleInput) (*aws.Request, *s3.PutBucketLifecycleOutput)
PutBucketLifecycle(*s3.PutBucketLifecycleInput) (*s3.PutBucketLifecycleOutput, error)
PutBucketLoggingRequest(*s3.PutBucketLoggingInput) (*aws.Request, *s3.PutBucketLoggingOutput)
PutBucketLogging(*s3.PutBucketLoggingInput) (*s3.PutBucketLoggingOutput, error)
PutBucketNotificationRequest(*s3.PutBucketNotificationInput) (*aws.Request, *s3.PutBucketNotificationOutput)
PutBucketNotification(*s3.PutBucketNotificationInput) (*s3.PutBucketNotificationOutput, error)
PutBucketNotificationConfigurationRequest(*s3.PutBucketNotificationConfigurationInput) (*aws.Request, *s3.PutBucketNotificationConfigurationOutput)
PutBucketNotificationConfiguration(*s3.PutBucketNotificationConfigurationInput) (*s3.PutBucketNotificationConfigurationOutput, error)
PutBucketPolicyRequest(*s3.PutBucketPolicyInput) (*aws.Request, *s3.PutBucketPolicyOutput)
PutBucketPolicy(*s3.PutBucketPolicyInput) (*s3.PutBucketPolicyOutput, error)
PutBucketReplicationRequest(*s3.PutBucketReplicationInput) (*aws.Request, *s3.PutBucketReplicationOutput)
PutBucketReplication(*s3.PutBucketReplicationInput) (*s3.PutBucketReplicationOutput, error)
PutBucketRequestPaymentRequest(*s3.PutBucketRequestPaymentInput) (*aws.Request, *s3.PutBucketRequestPaymentOutput)
PutBucketRequestPayment(*s3.PutBucketRequestPaymentInput) (*s3.PutBucketRequestPaymentOutput, error)
PutBucketTaggingRequest(*s3.PutBucketTaggingInput) (*aws.Request, *s3.PutBucketTaggingOutput)
PutBucketTagging(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error)
PutBucketVersioningRequest(*s3.PutBucketVersioningInput) (*aws.Request, *s3.PutBucketVersioningOutput)
PutBucketVersioning(*s3.PutBucketVersioningInput) (*s3.PutBucketVersioningOutput, error)
PutBucketWebsiteRequest(*s3.PutBucketWebsiteInput) (*aws.Request, *s3.PutBucketWebsiteOutput)
PutBucketWebsite(*s3.PutBucketWebsiteInput) (*s3.PutBucketWebsiteOutput, error)
PutObjectRequest(*s3.PutObjectInput) (*aws.Request, *s3.PutObjectOutput)
PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error)
PutObjectACLRequest(*s3.PutObjectACLInput) (*aws.Request, *s3.PutObjectACLOutput)
PutObjectACL(*s3.PutObjectACLInput) (*s3.PutObjectACLOutput, error)
RestoreObjectRequest(*s3.RestoreObjectInput) (*aws.Request, *s3.RestoreObjectOutput)
RestoreObject(*s3.RestoreObjectInput) (*s3.RestoreObjectOutput, error)
UploadPartRequest(*s3.UploadPartInput) (*aws.Request, *s3.UploadPartOutput)
UploadPart(*s3.UploadPartInput) (*s3.UploadPartOutput, error)
UploadPartCopyRequest(*s3.UploadPartCopyInput) (*aws.Request, *s3.UploadPartCopyOutput)
UploadPartCopy(*s3.UploadPartCopyInput) (*s3.UploadPartCopyOutput, error)
}

View file

@ -13,7 +13,7 @@ import (
var _ = unit.Imported
func TestSSECustomerKeyOverHTTPError(t *testing.T) {
s := s3.New(&aws.Config{DisableSSL: true})
s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)})
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
Bucket: aws.String("bucket"),
CopySource: aws.String("bucket/source"),
@ -28,7 +28,7 @@ func TestSSECustomerKeyOverHTTPError(t *testing.T) {
}
func TestCopySourceSSECustomerKeyOverHTTPError(t *testing.T) {
s := s3.New(&aws.Config{DisableSSL: true})
s := s3.New(&aws.Config{DisableSSL: aws.Bool(true)})
req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{
Bucket: aws.String("bucket"),
CopySource: aws.String("bucket/source"),

View file

@ -1,270 +0,0 @@
package aws
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"os/user"
"path"
"sync"
"time"
"github.com/vaughan0/go-ini"
)
// Credentials are used to authenticate and authorize calls that you make to
// AWS.
type Credentials struct {
AccessKeyID string
SecretAccessKey string
SecurityToken string
}
// A CredentialsProvider is a provider of credentials.
type CredentialsProvider interface {
// Credentials returns a set of credentials (or an error if no credentials
// could be provided).
Credentials() (*Credentials, error)
}
var (
// ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
// found in the process's environment.
ErrAccessKeyIDNotFound = fmt.Errorf("AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment")
// ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
// can't be found in the process's environment.
ErrSecretAccessKeyNotFound = fmt.Errorf("AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment")
)
// Context encapsulates the context of a client's connection to an AWS service.
type Context struct {
Service string
Region string
Credentials CredentialsProvider
}
var currentTime = func() time.Time {
return time.Now()
}
// DetectCreds returns a CredentialsProvider based on the available information.
//
// If the access key ID and secret access key are provided, it returns a basic
// provider.
//
// If credentials are available via environment variables, it returns an
// environment provider.
//
// If a profile configuration file is available in the default location and has
// a default profile configured, it returns a profile provider.
//
// Otherwise, it returns an IAM instance provider.
func DetectCreds(accessKeyID, secretAccessKey, securityToken string) CredentialsProvider {
if accessKeyID != "" && secretAccessKey != "" {
return Creds(accessKeyID, secretAccessKey, securityToken)
}
env, err := EnvCreds()
if err == nil {
return env
}
profile, err := ProfileCreds("", "", 10*time.Minute)
if err != nil {
return IAMCreds()
}
_, err = profile.Credentials()
if err != nil {
return IAMCreds()
}
return profile
}
// EnvCreds returns a static provider of AWS credentials from the process's
// environment, or an error if none are found.
func EnvCreds() (CredentialsProvider, error) {
id := os.Getenv("AWS_ACCESS_KEY_ID")
if id == "" {
id = os.Getenv("AWS_ACCESS_KEY")
}
secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
if secret == "" {
secret = os.Getenv("AWS_SECRET_KEY")
}
if id == "" {
return nil, ErrAccessKeyIDNotFound
}
if secret == "" {
return nil, ErrSecretAccessKeyNotFound
}
return Creds(id, secret, os.Getenv("AWS_SESSION_TOKEN")), nil
}
// Creds returns a static provider of credentials.
func Creds(accessKeyID, secretAccessKey, securityToken string) CredentialsProvider {
return staticCredentialsProvider{
creds: Credentials{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
SecurityToken: securityToken,
},
}
}
// IAMCreds returns a provider which pulls credentials from the local EC2
// instance's IAM roles.
func IAMCreds() CredentialsProvider {
return &iamProvider{}
}
// ProfileCreds returns a provider which pulls credentials from the profile
// configuration file.
func ProfileCreds(filename, profile string, expiry time.Duration) (CredentialsProvider, error) {
if filename == "" {
u, err := user.Current()
if err != nil {
return nil, err
}
filename = path.Join(u.HomeDir, ".aws", "credentials")
}
if profile == "" {
profile = "default"
}
return &profileProvider{
filename: filename,
profile: profile,
expiry: expiry,
}, nil
}
type profileProvider struct {
filename string
profile string
expiry time.Duration
creds Credentials
m sync.Mutex
expiration time.Time
}
func (p *profileProvider) Credentials() (*Credentials, error) {
p.m.Lock()
defer p.m.Unlock()
if p.expiration.After(currentTime()) {
return &p.creds, nil
}
config, err := ini.LoadFile(p.filename)
if err != nil {
return nil, err
}
profile := config.Section(p.profile)
accessKeyID, ok := profile["aws_access_key_id"]
if !ok {
return nil, fmt.Errorf("profile %s in %s did not contain aws_access_key_id", p.profile, p.filename)
}
secretAccessKey, ok := profile["aws_secret_access_key"]
if !ok {
return nil, fmt.Errorf("profile %s in %s did not contain aws_secret_access_key", p.profile, p.filename)
}
securityToken := profile["aws_session_token"]
p.creds = Credentials{
AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
SecurityToken: securityToken,
}
p.expiration = currentTime().Add(p.expiry)
return &p.creds, nil
}
type iamProvider struct {
creds Credentials
m sync.Mutex
expiration time.Time
}
var metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
// IAMClient is the HTTP client used to query the metadata endpoint for IAM
// credentials.
var IAMClient = http.Client{
Timeout: 1 * time.Second,
}
func (p *iamProvider) Credentials() (*Credentials, error) {
p.m.Lock()
defer p.m.Unlock()
if p.expiration.After(currentTime()) {
return &p.creds, nil
}
var body struct {
Expiration time.Time
AccessKeyID string
SecretAccessKey string
Token string
}
resp, err := IAMClient.Get(metadataCredentialsEndpoint)
if err != nil {
return nil, fmt.Errorf("listing IAM credentials")
}
defer func() {
_ = resp.Body.Close()
}()
// Take the first line of the body of the metadata endpoint
s := bufio.NewScanner(resp.Body)
if !s.Scan() {
return nil, fmt.Errorf("unable to find default IAM credentials")
} else if s.Err() != nil {
return nil, fmt.Errorf("%s listing IAM credentials", s.Err())
}
resp, err = IAMClient.Get(metadataCredentialsEndpoint + s.Text())
if err != nil {
return nil, fmt.Errorf("getting %s IAM credentials", s.Text())
}
defer func() {
_ = resp.Body.Close()
}()
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return nil, fmt.Errorf("decoding %s IAM credentials", s.Text())
}
p.creds = Credentials{
AccessKeyID: body.AccessKeyID,
SecretAccessKey: body.SecretAccessKey,
SecurityToken: body.Token,
}
p.expiration = body.Expiration
return &p.creds, nil
}
type staticCredentialsProvider struct {
creds Credentials
}
func (p staticCredentialsProvider) Credentials() (*Credentials, error) {
return &p.creds, nil
}

View file

@ -1,236 +0,0 @@
package aws
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)
func TestEnvCreds(t *testing.T) {
os.Clearenv()
os.Setenv("AWS_ACCESS_KEY_ID", "access")
os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
os.Setenv("AWS_SESSION_TOKEN", "token")
prov, err := EnvCreds()
if err != nil {
t.Fatal(err)
}
creds, err := prov.Credentials()
if err != nil {
t.Fatal(err)
}
if v, want := creds.AccessKeyID, "access"; v != want {
t.Errorf("Access key ID was %v, expected %v", v, want)
}
if v, want := creds.SecretAccessKey, "secret"; v != want {
t.Errorf("Secret access key was %v, expected %v", v, want)
}
if v, want := creds.SecurityToken, "token"; v != want {
t.Errorf("Security token was %v, expected %v", v, want)
}
}
func TestEnvCredsNoAccessKeyID(t *testing.T) {
os.Clearenv()
os.Setenv("AWS_SECRET_ACCESS_KEY", "secret")
prov, err := EnvCreds()
if err != ErrAccessKeyIDNotFound {
t.Fatalf("ErrAccessKeyIDNotFound expected, but was %#v/%#v", prov, err)
}
}
func TestEnvCredsNoSecretAccessKey(t *testing.T) {
os.Clearenv()
os.Setenv("AWS_ACCESS_KEY_ID", "access")
prov, err := EnvCreds()
if err != ErrSecretAccessKeyNotFound {
t.Fatalf("ErrSecretAccessKeyNotFound expected, but was %#v/%#v", prov, err)
}
}
func TestEnvCredsAlternateNames(t *testing.T) {
os.Clearenv()
os.Setenv("AWS_ACCESS_KEY", "access")
os.Setenv("AWS_SECRET_KEY", "secret")
prov, err := EnvCreds()
if err != nil {
t.Fatal(err)
}
creds, err := prov.Credentials()
if err != nil {
t.Fatal(err)
}
if v, want := creds.AccessKeyID, "access"; v != want {
t.Errorf("Access key ID was %v, expected %v", v, want)
}
if v, want := creds.SecretAccessKey, "secret"; v != want {
t.Errorf("Secret access key was %v, expected %v", v, want)
}
}
func TestIAMCreds(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/" {
fmt.Fprintln(w, "/creds")
} else {
fmt.Fprintln(w, `{
"AccessKeyId" : "accessKey",
"SecretAccessKey" : "secret",
"Token" : "token",
"Expiration" : "2014-12-16T01:51:37Z"
}`)
}
}))
defer server.Close()
defer func(s string) {
metadataCredentialsEndpoint = s
}(metadataCredentialsEndpoint)
metadataCredentialsEndpoint = server.URL
defer func() {
currentTime = time.Now
}()
currentTime = func() time.Time {
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
}
prov := IAMCreds()
creds, err := prov.Credentials()
if err != nil {
t.Fatal(err)
}
if v, want := creds.AccessKeyID, "accessKey"; v != want {
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
}
if v, want := creds.SecretAccessKey, "secret"; v != want {
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
}
if v, want := creds.SecurityToken, "token"; v != want {
t.Errorf("SecurityToken was %v, but expected %v", v, want)
}
}
func TestProfileCreds(t *testing.T) {
prov, err := ProfileCreds("example.ini", "", 10*time.Minute)
if err != nil {
t.Fatal(err)
}
creds, err := prov.Credentials()
if err != nil {
t.Fatal(err)
}
if v, want := creds.AccessKeyID, "accessKey"; v != want {
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
}
if v, want := creds.SecretAccessKey, "secret"; v != want {
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
}
if v, want := creds.SecurityToken, "token"; v != want {
t.Errorf("SecurityToken was %v, but expected %v", v, want)
}
}
func TestProfileCredsWithoutToken(t *testing.T) {
prov, err := ProfileCreds("example.ini", "no_token", 10*time.Minute)
if err != nil {
t.Fatal(err)
}
creds, err := prov.Credentials()
if err != nil {
t.Fatal(err)
}
if v, want := creds.AccessKeyID, "accessKey"; v != want {
t.Errorf("AcccessKeyID was %v, but expected %v", v, want)
}
if v, want := creds.SecretAccessKey, "secret"; v != want {
t.Errorf("SecretAccessKey was %v, but expected %v", v, want)
}
if v, want := creds.SecurityToken, ""; v != want {
t.Errorf("SecurityToken was %v, but expected %v", v, want)
}
}
func BenchmarkProfileCreds(b *testing.B) {
prov, err := ProfileCreds("example.ini", "", 10*time.Minute)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := prov.Credentials()
if err != nil {
b.Fatal(err)
}
}
})
}
func BenchmarkIAMCreds(b *testing.B) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/" {
fmt.Fprintln(w, "/creds")
} else {
fmt.Fprintln(w, `{
"AccessKeyId" : "accessKey",
"SecretAccessKey" : "secret",
"Token" : "token",
"Expiration" : "2014-12-16T01:51:37Z"
}`)
}
}))
defer server.Close()
defer func(s string) {
metadataCredentialsEndpoint = s
}(metadataCredentialsEndpoint)
metadataCredentialsEndpoint = server.URL
defer func() {
currentTime = time.Now
}()
currentTime = func() time.Time {
return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC)
}
b.ResetTimer()
prov := IAMCreds()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, err := prov.Credentials()
if err != nil {
b.Fatal(err)
}
}
})
}

View file

@ -1,3 +0,0 @@
// Package aws contains support code for the various AWS clients in the
// github.com/hashicorp/aws-sdk-go/gen subpackages.
package aws

View file

@ -1,182 +0,0 @@
package aws
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
// EC2Client is the underlying client for EC2 APIs.
type EC2Client struct {
Context Context
Client *http.Client
Endpoint string
APIVersion string
}
// Do sends an HTTP request and returns an HTTP response, following policy
// (e.g. redirects, cookies, auth) as configured on the client.
func (c *EC2Client) Do(op, method, uri string, req, resp interface{}) error {
body := url.Values{"Action": {op}, "Version": {c.APIVersion}}
if err := c.loadValues(body, req, ""); err != nil {
return err
}
httpReq, err := http.NewRequest(method, c.Endpoint+uri, strings.NewReader(body.Encode()))
if err != nil {
return err
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpReq.Header.Set("User-Agent", "aws-go")
if err := c.Context.sign(httpReq); err != nil {
return err
}
httpResp, err := c.Client.Do(httpReq)
if err != nil {
return err
}
defer func() {
_ = httpResp.Body.Close()
}()
if httpResp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return err
}
if len(bodyBytes) == 0 {
return APIError{
StatusCode: httpResp.StatusCode,
Message: httpResp.Status,
}
}
var ec2Err ec2ErrorResponse
if err := xml.Unmarshal(bodyBytes, &ec2Err); err != nil {
return err
}
return ec2Err.Err(httpResp.StatusCode)
}
if resp != nil {
return xml.NewDecoder(httpResp.Body).Decode(resp)
}
return nil
}
type ec2ErrorResponse struct {
XMLName xml.Name `xml:"Response"`
Type string `xml:"Errors>Error>Type"`
Code string `xml:"Errors>Error>Code"`
Message string `xml:"Errors>Error>Message"`
RequestID string `xml:"RequestID"`
}
func (e ec2ErrorResponse) Err(StatusCode int) error {
return APIError{
StatusCode: StatusCode,
Type: e.Type,
Code: e.Code,
Message: e.Message,
RequestID: e.RequestID,
}
}
func (c *EC2Client) loadValues(v url.Values, i interface{}, prefix string) error {
value := reflect.ValueOf(i)
// follow any pointers
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
if value.Kind() == reflect.Invalid {
return nil
}
if casted, ok := value.Interface().([]byte); ok && prefix != "" {
v.Set(prefix, string(casted))
return nil
}
if value.Kind() == reflect.Slice {
for i := 0; i < value.Len(); i++ {
vPrefix := prefix
if vPrefix == "" {
vPrefix = strconv.Itoa(i + 1)
} else {
vPrefix = vPrefix + "." + strconv.Itoa(i+1)
}
if err := c.loadValues(v, value.Index(i).Interface(), vPrefix); err != nil {
return err
}
}
return nil
}
return c.loadStruct(v, value, prefix)
}
func (c *EC2Client) loadStruct(v url.Values, value reflect.Value, prefix string) error {
if !value.IsValid() {
return nil
}
t := value.Type()
for i := 0; i < value.NumField(); i++ {
value := value.Field(i)
name := t.Field(i).Tag.Get("ec2")
if name == "" {
name = t.Field(i).Name
}
if prefix != "" {
name = prefix + "." + name
}
switch casted := value.Interface().(type) {
case StringValue:
if casted != nil {
v.Set(name, *casted)
}
case BooleanValue:
if casted != nil {
v.Set(name, strconv.FormatBool(*casted))
}
case LongValue:
if casted != nil {
v.Set(name, strconv.FormatInt(*casted, 10))
}
case IntegerValue:
if casted != nil {
v.Set(name, strconv.Itoa(*casted))
}
case DoubleValue:
if casted != nil {
v.Set(name, strconv.FormatFloat(*casted, 'f', -1, 64))
}
case FloatValue:
if casted != nil {
v.Set(name, strconv.FormatFloat(float64(*casted), 'f', -1, 32))
}
case []string:
if len(casted) != 0 {
for i, val := range casted {
v.Set(fmt.Sprintf("%s.%d", name, i+1), val)
}
}
case time.Time:
if !casted.IsZero() {
const ISO8601UTC = "2006-01-02T15:04:05Z"
v.Set(name, casted.UTC().Format(ISO8601UTC))
}
default:
if err := c.loadValues(v, value.Interface(), name); err != nil {
return err
}
}
}
return nil
}

View file

@ -1,227 +0,0 @@
package aws_test
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"sync"
"testing"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
)
func TestEC2Request(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
var form url.Values
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
form = r.Form
fmt.Fprintln(w, `<Thing><IpAddress>woo</IpAddress></Thing>`)
},
))
defer server.Close()
client := aws.EC2Client{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
APIVersion: "1.1",
}
req := fakeEC2Request{
PresentString: aws.String("string"),
PresentBoolean: aws.True(),
PresentInteger: aws.Integer(1),
PresentLong: aws.Long(2),
PresentDouble: aws.Double(1.2),
PresentFloat: aws.Float(2.3),
PresentTime: time.Date(2001, 1, 1, 2, 1, 1, 0, time.FixedZone("UTC+1", 3600)),
PresentSlice: []string{"one", "two"},
PresentStruct: &EmbeddedStruct{Value: aws.String("v")},
PresentStructSlice: []EmbeddedStruct{
{Value: aws.String("p")},
{Value: aws.String("q")},
},
}
var resp fakeEC2Response
if err := client.Do("GetIP", "POST", "/", &req, &resp); err != nil {
t.Fatal(err)
}
m.Lock()
defer m.Unlock()
if v, want := httpReq.Method, "POST"; v != want {
t.Errorf("Method was %v but expected %v", v, want)
}
if httpReq.Header.Get("Authorization") == "" {
t.Error("Authorization header is missing")
}
if v, want := httpReq.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; v != want {
t.Errorf("Content-Type was %v but expected %v", v, want)
}
if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want {
t.Errorf("User-Agent was %v but expected %v", v, want)
}
if err := httpReq.ParseForm(); err != nil {
t.Fatal(err)
}
expectedForm := url.Values{
"Action": []string{"GetIP"},
"Version": []string{"1.1"},
"PresentString": []string{"string"},
"PresentBoolean": []string{"true"},
"PresentInteger": []string{"1"},
"PresentLong": []string{"2"},
"PresentDouble": []string{"1.2"},
"PresentFloat": []string{"2.3"},
"PresentTime": []string{"2001-01-01T01:01:01Z"},
"PresentSlice.1": []string{"one"},
"PresentSlice.2": []string{"two"},
"PresentStruct.Value": []string{"v"},
"PresentStructSlice.1.Value": []string{"p"},
"PresentStructSlice.2.Value": []string{"q"},
}
if !reflect.DeepEqual(form, expectedForm) {
t.Errorf("Post body was \n%s\n but expected \n%s", form.Encode(), expectedForm.Encode())
}
if want := (fakeEC2Response{IPAddress: "woo"}); want != resp {
t.Errorf("Response was %#v, but expected %#v", resp, want)
}
}
func TestEC2RequestError(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
var form url.Values
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
form = r.Form
w.WriteHeader(400)
fmt.Fprintln(w, `<Response>
<RequestId>woo</RequestId>
<Errors>
<Error>
<Type>Problem</Type>
<Code>Uh Oh</Code>
<Message>You done did it</Message>
</Error>
</Errors>
</Response>`)
},
))
defer server.Close()
client := aws.EC2Client{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
APIVersion: "1.1",
}
req := fakeEC2Request{}
var resp fakeEC2Response
err := client.Do("GetIP", "POST", "/", &req, &resp)
if err == nil {
t.Fatal("Expected an error but none was returned")
}
if err, ok := err.(aws.APIError); ok {
if v, want := err.Type, "Problem"; v != want {
t.Errorf("Error type was %v, but expected %v", v, want)
}
if v, want := err.Code, "Uh Oh"; v != want {
t.Errorf("Error type was %v, but expected %v", v, want)
}
if v, want := err.Message, "You done did it"; v != want {
t.Errorf("Error message was %v, but expected %v", v, want)
}
} else {
t.Errorf("Unknown error returned: %#v", err)
}
}
type fakeEC2Request struct {
PresentString aws.StringValue `ec2:"PresentString"`
MissingString aws.StringValue `ec2:"MissingString"`
PresentInteger aws.IntegerValue `ec2:"PresentInteger"`
MissingInteger aws.IntegerValue `ec2:"MissingInteger"`
PresentLong aws.LongValue `ec2:"PresentLong"`
MissingLong aws.LongValue `ec2:"MissingLong"`
PresentDouble aws.DoubleValue `ec2:"PresentDouble"`
MissingDouble aws.DoubleValue `ec2:"MissingDouble"`
PresentFloat aws.FloatValue `ec2:"PresentFloat"`
MissingFloat aws.FloatValue `ec2:"MissingFloat"`
PresentTime time.Time `ec2:"PresentTime"`
MissingTime time.Time `ec2:"MissingTime"`
PresentBoolean aws.BooleanValue `ec2:"PresentBoolean"`
MissingBoolean aws.BooleanValue `ec2:"MissingBoolean"`
PresentSlice []string `ec2:"PresentSlice"`
MissingSlice []string `ec2:"MissingSlice"`
PresentStructSlice []EmbeddedStruct `ec2:"PresentStructSlice"`
MissingStructSlice []EmbeddedStruct `ec2:"MissingStructSlice"`
PresentStruct *EmbeddedStruct `ec2:"PresentStruct"`
MissingStruct *EmbeddedStruct `ec2:"MissingStruct"`
}
type fakeEC2Response struct {
IPAddress string `xml:"IpAddress"`
}

View file

@ -1,16 +0,0 @@
package aws
// An APIError is an error returned by an AWS API.
type APIError struct {
StatusCode int // HTTP status code e.g. 200
Type string
Code string
Message string
RequestID string
HostID string
Specifics map[string]string
}
func (e APIError) Error() string {
return e.Message
}

View file

@ -1,8 +0,0 @@
[default]
aws_access_key_id = accessKey
aws_secret_access_key = secret
aws_session_token = token
[no_token]
aws_access_key_id = accessKey
aws_secret_access_key = secret

View file

@ -1,81 +0,0 @@
package aws
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
// JSONClient is the underlying client for JSON APIs.
type JSONClient struct {
Context Context
Client *http.Client
Endpoint string
TargetPrefix string
JSONVersion string
}
// Do sends an HTTP request and returns an HTTP response, following policy
// (e.g. redirects, cookies, auth) as configured on the client.
func (c *JSONClient) Do(op, method, uri string, req, resp interface{}) error {
b, err := json.Marshal(req)
if err != nil {
return err
}
httpReq, err := http.NewRequest(method, c.Endpoint+uri, bytes.NewReader(b))
if err != nil {
return err
}
httpReq.Header.Set("User-Agent", "aws-go")
httpReq.Header.Set("X-Amz-Target", c.TargetPrefix+"."+op)
httpReq.Header.Set("Content-Type", "application/x-amz-json-"+c.JSONVersion)
if err := c.Context.sign(httpReq); err != nil {
return err
}
httpResp, err := c.Client.Do(httpReq)
if err != nil {
return err
}
defer func() {
_ = httpResp.Body.Close()
}()
if httpResp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return err
}
if len(bodyBytes) == 0 {
return APIError{
StatusCode: httpResp.StatusCode,
Message: httpResp.Status,
}
}
var jsonErr jsonErrorResponse
if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
return err
}
return jsonErr.Err(httpResp.StatusCode)
}
if resp != nil {
return json.NewDecoder(httpResp.Body).Decode(resp)
}
return nil
}
type jsonErrorResponse struct {
Type string `json:"__type"`
Message string `json:"message"`
}
func (e jsonErrorResponse) Err(StatusCode int) error {
return APIError{
StatusCode: StatusCode,
Type: e.Type,
Message: e.Message,
}
}

View file

@ -1,143 +0,0 @@
package aws_test
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/hashicorp/aws-sdk-go/aws"
)
func TestJSONRequest(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
var body []byte
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
defer r.Body.Close()
httpReq = r
body = b
fmt.Fprintln(w, `{"TailWagged":true}`)
},
))
defer server.Close()
client := aws.JSONClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
TargetPrefix: "Animals",
JSONVersion: "1.1",
}
req := fakeJSONRequest{Name: "Penny"}
var resp fakeJSONResponse
if err := client.Do("PetTheDog", "POST", "/", req, &resp); err != nil {
t.Fatal(err)
}
m.Lock()
defer m.Unlock()
if v, want := httpReq.Method, "POST"; v != want {
t.Errorf("Method was %v but expected %v", v, want)
}
if httpReq.Header.Get("Authorization") == "" {
t.Error("Authorization header is missing")
}
if v, want := httpReq.Header.Get("Content-Type"), "application/x-amz-json-1.1"; v != want {
t.Errorf("Content-Type was %v but expected %v", v, want)
}
if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want {
t.Errorf("User-Agent was %v but expected %v", v, want)
}
if v, want := httpReq.Header.Get("X-Amz-Target"), "Animals.PetTheDog"; v != want {
t.Errorf("X-Amz-Target was %v but expected %v", v, want)
}
if v, want := string(body), `{"Name":"Penny"}`; v != want {
t.Errorf("Body was %v but expected %v", v, want)
}
if v, want := resp, (fakeJSONResponse{TailWagged: true}); v != want {
t.Errorf("Response was %#v but expected %#v", v, want)
}
}
func TestJSONRequestError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(400)
fmt.Fprintln(w, `{"__type":"Problem", "message":"What even"}`)
},
))
defer server.Close()
client := aws.JSONClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
TargetPrefix: "Animals",
JSONVersion: "1.1",
}
req := fakeJSONRequest{Name: "Penny"}
var resp fakeJSONResponse
err := client.Do("PetTheDog", "POST", "/", req, &resp)
if err == nil {
t.Fatal("Expected an error but none was returned")
}
if err, ok := err.(aws.APIError); ok {
if v, want := err.Type, "Problem"; v != want {
t.Errorf("Error type was %v, but expected %v", v, want)
}
if v, want := err.Message, "What even"; v != want {
t.Errorf("Error message was %v, but expected %v", v, want)
}
} else {
t.Errorf("Unknown error returned: %#v", err)
}
}
type fakeJSONRequest struct {
Name string
}
type fakeJSONResponse struct {
TailWagged bool
}

View file

@ -1,234 +0,0 @@
package aws
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
// QueryClient is the underlying client for Query APIs.
type QueryClient struct {
Context Context
Client *http.Client
Endpoint string
APIVersion string
}
// Do sends an HTTP request and returns an HTTP response, following policy
// (e.g. redirects, cookies, auth) as configured on the client.
func (c *QueryClient) Do(op, method, uri string, req, resp interface{}) error {
body := url.Values{"Action": {op}, "Version": {c.APIVersion}}
if err := c.loadValues(body, req, ""); err != nil {
return err
}
httpReq, err := http.NewRequest(method, c.Endpoint+uri, strings.NewReader(body.Encode()))
if err != nil {
return err
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpReq.Header.Set("User-Agent", "aws-go")
if err := c.Context.sign(httpReq); err != nil {
return err
}
httpResp, err := c.Client.Do(httpReq)
if err != nil {
return err
}
defer func() {
_ = httpResp.Body.Close()
}()
if httpResp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return err
}
if len(bodyBytes) == 0 {
return APIError{
StatusCode: httpResp.StatusCode,
Message: httpResp.Status,
}
}
var queryErr queryErrorResponse
if err := xml.Unmarshal(bodyBytes, &queryErr); err != nil {
return err
}
return queryErr.Err(httpResp.StatusCode)
}
if resp != nil {
return xml.NewDecoder(httpResp.Body).Decode(resp)
}
return nil
}
type queryErrorResponse struct {
XMLName xml.Name `xml:"ErrorResponse"`
Type string `xml:"Error>Type"`
Code string `xml:"Error>Code"`
Message string `xml:"Error>Message"`
RequestID string `xml:"RequestId"`
}
func (e queryErrorResponse) Err(StatusCode int) error {
return APIError{
StatusCode: StatusCode,
Type: e.Type,
Code: e.Code,
Message: e.Message,
RequestID: e.RequestID,
}
}
func (c *QueryClient) loadValues(v url.Values, i interface{}, prefix string) error {
value := reflect.ValueOf(i)
// follow any pointers
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
// no need to handle zero values
if !value.IsValid() {
return nil
}
switch value.Kind() {
case reflect.Struct:
return c.loadStruct(v, value, prefix)
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
slicePrefix := prefix
if slicePrefix == "" {
slicePrefix = strconv.Itoa(i + 1)
} else {
slicePrefix = slicePrefix + "." + strconv.Itoa(i+1)
}
if err := c.loadValues(v, value.Index(i).Interface(), slicePrefix); err != nil {
return err
}
}
return nil
case reflect.Map:
sortedKeys := []string{}
keysByString := map[string]reflect.Value{}
for _, k := range value.MapKeys() {
s := fmt.Sprintf("%v", k.Interface())
sortedKeys = append(sortedKeys, s)
keysByString[s] = k
}
sort.Strings(sortedKeys)
for i, sortKey := range sortedKeys {
mapKey := keysByString[sortKey]
var keyName string
if prefix == "" {
keyName = strconv.Itoa(i+1) + ".Name"
} else {
keyName = prefix + "." + strconv.Itoa(i+1) + ".Name"
}
if err := c.loadValue(v, mapKey, keyName); err != nil {
return err
}
mapValue := value.MapIndex(mapKey)
var valueName string
if prefix == "" {
valueName = strconv.Itoa(i+1) + ".Value"
} else {
valueName = prefix + "." + strconv.Itoa(i+1) + ".Value"
}
if err := c.loadValue(v, mapValue, valueName); err != nil {
return err
}
}
return nil
default:
panic("unknown request member type: " + value.String())
}
}
func (c *QueryClient) loadStruct(v url.Values, value reflect.Value, prefix string) error {
if !value.IsValid() {
return nil
}
t := value.Type()
for i := 0; i < value.NumField(); i++ {
value := value.Field(i)
name := t.Field(i).Tag.Get("query")
if name == "" {
name = t.Field(i).Name
}
if prefix != "" {
name = prefix + "." + name
}
if err := c.loadValue(v, value, name); err != nil {
return err
}
}
return nil
}
func (c *QueryClient) loadValue(v url.Values, value reflect.Value, name string) error {
switch casted := value.Interface().(type) {
case string:
if casted != "" {
v.Set(name, casted)
}
case StringValue:
if casted != nil {
v.Set(name, *casted)
}
case BooleanValue:
if casted != nil {
v.Set(name, strconv.FormatBool(*casted))
}
case LongValue:
if casted != nil {
v.Set(name, strconv.FormatInt(*casted, 10))
}
case IntegerValue:
if casted != nil {
v.Set(name, strconv.Itoa(*casted))
}
case DoubleValue:
if casted != nil {
v.Set(name, strconv.FormatFloat(*casted, 'f', -1, 64))
}
case FloatValue:
if casted != nil {
v.Set(name, strconv.FormatFloat(float64(*casted), 'f', -1, 32))
}
case time.Time:
if !casted.IsZero() {
const ISO8601UTC = "2006-01-02T15:04:05Z"
v.Set(name, casted.UTC().Format(ISO8601UTC))
}
case []string:
if len(casted) != 0 {
for i, val := range casted {
v.Set(fmt.Sprintf("%s.%d", name, i+1), val)
}
}
default:
if err := c.loadValues(v, value.Interface(), name); err != nil {
return err
}
}
return nil
}

View file

@ -1,240 +0,0 @@
package aws_test
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"sync"
"testing"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
)
func TestQueryRequest(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
var form url.Values
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
form = r.Form
fmt.Fprintln(w, `<Thing><IpAddress>woo</IpAddress></Thing>`)
},
))
defer server.Close()
client := aws.QueryClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
APIVersion: "1.1",
}
req := fakeQueryRequest{
PresentString: aws.String("string"),
PresentBoolean: aws.True(),
PresentInteger: aws.Integer(1),
PresentLong: aws.Long(2),
PresentDouble: aws.Double(1.2),
PresentFloat: aws.Float(2.3),
PresentTime: time.Date(2001, 1, 1, 2, 1, 1, 0, time.FixedZone("UTC+1", 3600)),
PresentSlice: []string{"one", "two"},
PresentStruct: &EmbeddedStruct{Value: aws.String("v")},
PresentStructSlice: []EmbeddedStruct{
{Value: aws.String("p")},
{Value: aws.String("q")},
},
PresentMap: map[string]EmbeddedStruct{
"aa": EmbeddedStruct{Value: aws.String("AA")},
"bb": EmbeddedStruct{Value: aws.String("BB")},
},
}
var resp fakeQueryResponse
if err := client.Do("GetIP", "POST", "/", &req, &resp); err != nil {
t.Fatal(err)
}
m.Lock()
defer m.Unlock()
if v, want := httpReq.Method, "POST"; v != want {
t.Errorf("Method was %v but expected %v", v, want)
}
if httpReq.Header.Get("Authorization") == "" {
t.Error("Authorization header is missing")
}
if v, want := httpReq.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; v != want {
t.Errorf("Content-Type was %v but expected %v", v, want)
}
if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want {
t.Errorf("User-Agent was %v but expected %v", v, want)
}
if err := httpReq.ParseForm(); err != nil {
t.Fatal(err)
}
expectedForm := url.Values{
"Action": []string{"GetIP"},
"Version": []string{"1.1"},
"PresentString": []string{"string"},
"PresentBoolean": []string{"true"},
"PresentInteger": []string{"1"},
"PresentLong": []string{"2"},
"PresentDouble": []string{"1.2"},
"PresentFloat": []string{"2.3"},
"PresentTime": []string{"2001-01-01T01:01:01Z"},
"PresentSlice.1": []string{"one"},
"PresentSlice.2": []string{"two"},
"PresentStruct.Value": []string{"v"},
"PresentStructSlice.1.Value": []string{"p"},
"PresentStructSlice.2.Value": []string{"q"},
"PresentMap.1.Name": []string{"aa"},
"PresentMap.1.Value.Value": []string{"AA"},
"PresentMap.2.Name": []string{"bb"},
"PresentMap.2.Value.Value": []string{"BB"},
}
if !reflect.DeepEqual(form, expectedForm) {
t.Errorf("Post body was \n%s\n but expected \n%s", form.Encode(), expectedForm.Encode())
}
if want := (fakeQueryResponse{IPAddress: "woo"}); want != resp {
t.Errorf("Response was %#v, but expected %#v", resp, want)
}
}
func TestQueryRequestError(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
var form url.Values
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
form = r.Form
w.WriteHeader(400)
fmt.Fprintln(w, `<ErrorResponse>
<RequestId>woo</RequestId>
<Error>
<Type>Problem</Type>
<Code>Uh Oh</Code>
<Message>You done did it</Message>
</Error>
</ErrorResponse>`)
},
))
defer server.Close()
client := aws.QueryClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
Endpoint: server.URL,
APIVersion: "1.1",
}
req := fakeQueryRequest{}
var resp fakeQueryResponse
err := client.Do("GetIP", "POST", "/", &req, &resp)
if err == nil {
t.Fatal("Expected an error but none was returned")
}
if err, ok := err.(aws.APIError); ok {
if v, want := err.Type, "Problem"; v != want {
t.Errorf("Error type was %v, but expected %v", v, want)
}
if v, want := err.Code, "Uh Oh"; v != want {
t.Errorf("Error type was %v, but expected %v", v, want)
}
if v, want := err.Message, "You done did it"; v != want {
t.Errorf("Error message was %v, but expected %v", v, want)
}
} else {
t.Errorf("Unknown error returned: %#v", err)
}
}
type fakeQueryRequest struct {
PresentString aws.StringValue `query:"PresentString"`
MissingString aws.StringValue `query:"MissingString"`
PresentInteger aws.IntegerValue `query:"PresentInteger"`
MissingInteger aws.IntegerValue `query:"MissingInteger"`
PresentLong aws.LongValue `query:"PresentLong"`
MissingLong aws.LongValue `query:"MissingLong"`
PresentDouble aws.DoubleValue `query:"PresentDouble"`
MissingDouble aws.DoubleValue `query:"MissingDouble"`
PresentFloat aws.FloatValue `query:"PresentFloat"`
MissingFloat aws.FloatValue `query:"MissingFloat"`
PresentBoolean aws.BooleanValue `query:"PresentBoolean"`
MissingBoolean aws.BooleanValue `query:"MissingBoolean"`
PresentTime time.Time `query:"PresentTime"`
MissingTime time.Time `query:"MissingTime"`
PresentSlice []string `query:"PresentSlice"`
MissingSlice []string `query:"MissingSlice"`
PresentStructSlice []EmbeddedStruct `query:"PresentStructSlice"`
MissingStructSlice []EmbeddedStruct `query:"MissingStructSlice"`
PresentMap map[string]EmbeddedStruct `query:"PresentMap"`
MissingMap map[string]EmbeddedStruct `query:"MissingMap"`
PresentStruct *EmbeddedStruct `query:"PresentStruct"`
MissingStruct *EmbeddedStruct `query:"MissingStruct"`
}
type EmbeddedStruct struct {
Value aws.StringValue
}
type fakeQueryResponse struct {
IPAddress string `xml:"IpAddress"`
}

View file

@ -1,136 +0,0 @@
package aws
import (
"bytes"
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// RestClient is the underlying client for REST-JSON and REST-XML APIs.
type RestClient struct {
Context Context
Client *http.Client
Endpoint string
APIVersion string
}
// Whether the byte value can be sent without escaping in AWS URLs
var noEscape [256]bool
// Initialise noEscape
func init() {
for i := range noEscape {
// Amazon expects every character except these escaped
noEscape[i] = (i >= 'A' && i <= 'Z') ||
(i >= 'a' && i <= 'z') ||
(i >= '0' && i <= '9') ||
i == '-' ||
i == '.' ||
i == '/' ||
i == ':' ||
i == '_' ||
i == '~'
}
}
// EscapePath escapes part of a URL path in Amazon style
func EscapePath(path string) string {
var buf bytes.Buffer
for i := 0; i < len(path); i++ {
c := path[i]
if noEscape[c] {
buf.WriteByte(c)
} else {
buf.WriteByte('%')
buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16)))
}
}
return buf.String()
}
// Do sends an HTTP request and returns an HTTP response, following policy
// (e.g. redirects, cookies, auth) as configured on the client.
func (c *RestClient) Do(req *http.Request) (*http.Response, error) {
// Set the form for the URL
req.URL.Opaque = EscapePath(req.URL.Path)
req.Header.Set("User-Agent", "aws-go")
if err := c.Context.sign(req); err != nil {
return nil, err
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
bodyBytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
if len(bodyBytes) == 0 {
return nil, APIError{
StatusCode: resp.StatusCode,
Message: resp.Status,
}
}
var restErr restError
switch resp.Header.Get("Content-Type") {
case "application/json":
if err := json.Unmarshal(bodyBytes, &restErr); err != nil {
return nil, err
}
return nil, restErr.Err(resp.StatusCode)
case "application/xml", "text/xml":
// AWS XML error documents can have a couple of different formats.
// Try each before returning a decode error.
var wrappedErr restErrorResponse
if err := xml.Unmarshal(bodyBytes, &wrappedErr); err == nil {
return nil, wrappedErr.Error.Err(resp.StatusCode)
}
if err := xml.Unmarshal(bodyBytes, &restErr); err != nil {
return nil, err
}
return nil, restErr.Err(resp.StatusCode)
default:
return nil, APIError{
StatusCode: resp.StatusCode,
Message: string(bodyBytes),
}
}
}
return resp, nil
}
type restErrorResponse struct {
XMLName xml.Name `xml:"ErrorResponse",json:"-"`
Error restError
}
type restError struct {
XMLName xml.Name `xml:"Error",json:"-"`
Code string
BucketName string
Message string
RequestID string
HostID string
}
func (e restError) Err(StatusCode int) error {
return APIError{
StatusCode: StatusCode,
Code: e.Code,
Message: e.Message,
RequestID: e.RequestID,
HostID: e.HostID,
Specifics: map[string]string{
"BucketName": e.BucketName,
},
}
}

View file

@ -1,215 +0,0 @@
package aws_test
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/hashicorp/aws-sdk-go/aws"
)
func TestRestRequest(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
fmt.Fprintln(w, `woo`)
},
))
defer server.Close()
client := aws.RestClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
}
req, err := http.NewRequest("GET", server.URL+"/yay", nil)
if err != nil {
t.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if v, want := string(body), "woo\n"; v != want {
t.Errorf("Response entity was %q, but expected %q", v, want)
}
m.Lock()
defer m.Unlock()
if v, want := httpReq.Method, "GET"; v != want {
t.Errorf("Method was %v but expected %v", v, want)
}
if httpReq.Header.Get("Authorization") == "" {
t.Error("Authorization header is missing")
}
if v, want := httpReq.Header.Get("User-Agent"), "aws-go"; v != want {
t.Errorf("User-Agent was %v but expected %v", v, want)
}
if v, want := httpReq.URL.String(), "/yay"; v != want {
t.Errorf("URL was %v but expected %v", v, want)
}
}
func TestRestRequestXMLError(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(500)
fmt.Fprintln(w, `<Error>
<Code>bonus</Code>
<BucketName>bingo</BucketName>
<Message>the bad thing</Message>
<RequestId>woo woo</RequestId>
<HostId>woo woo</HostId>
</Error>`)
},
))
defer server.Close()
client := aws.RestClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
}
req, err := http.NewRequest("GET", server.URL+"/yay", nil)
if err != nil {
t.Fatal(err)
}
_, err = client.Do(req)
if err == nil {
t.Fatal("Expected an error but none was returned")
}
if err, ok := err.(aws.APIError); ok {
if v, want := err.Code, "bonus"; v != want {
t.Errorf("Error code was %v, but expected %v", v, want)
}
if v, want := err.Message, "the bad thing"; v != want {
t.Errorf("Error message was %v, but expected %v", v, want)
}
} else {
t.Errorf("Unknown error returned: %#v", err)
}
}
func TestRestRequestJSONError(t *testing.T) {
var m sync.Mutex
var httpReq *http.Request
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
m.Lock()
defer m.Unlock()
httpReq = r
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
fmt.Fprintln(w, `{"Code":"bonus", "Message":"the bad thing"}`)
},
))
defer server.Close()
client := aws.RestClient{
Context: aws.Context{
Service: "animals",
Region: "us-west-2",
Credentials: aws.Creds(
"accessKeyID",
"secretAccessKey",
"securityToken",
),
},
Client: http.DefaultClient,
}
req, err := http.NewRequest("GET", server.URL+"/yay", nil)
if err != nil {
t.Fatal(err)
}
_, err = client.Do(req)
if err == nil {
t.Fatal("Expected an error but none was returned")
}
if err, ok := err.(aws.APIError); ok {
if v, want := err.Code, "bonus"; v != want {
t.Errorf("Error code was %v, but expected %v", v, want)
}
if v, want := err.Message, "the bad thing"; v != want {
t.Errorf("Error message was %v, but expected %v", v, want)
}
} else {
t.Errorf("Unknown error returned: %#v", err)
}
}
func TestEscapePath(t *testing.T) {
for _, x := range []struct {
in string
want string
}{
{"", ""},
{"ABCDEFGHIJKLMNOPQRTSUVWXYZ", "ABCDEFGHIJKLMNOPQRTSUVWXYZ"},
{"abcdefghijklmnopqrtsuvwxyz", "abcdefghijklmnopqrtsuvwxyz"},
{"0123456789", "0123456789"},
{"_-~./:", "_-~./:"},
{"test? file", "test%3F%20file"},
{`hello? sausage/êé/Hello, 世界/ " ' @ < > & ?/z.txt`, "hello%3F%20sausage/%C3%AA%C3%A9/Hello%2C%20%E4%B8%96%E7%95%8C/%20%22%20%27%20%40%20%3C%20%3E%20%26%20%3F/z.txt"},
} {
got := aws.EscapePath(x.in)
if got != x.want {
t.Errorf("EscapePath(%q) got %q, want %v", x.in, got, x.want)
}
}
}

View file

@ -1,94 +0,0 @@
package aws
import (
"math"
"strconv"
"time"
)
// A StringValue is a string which may or may not be present.
type StringValue *string
// String converts a Go string into a StringValue.
func String(v string) StringValue {
return &v
}
// A BooleanValue is a boolean which may or may not be present.
type BooleanValue *bool
// Boolean converts a Go bool into a BooleanValue.
func Boolean(v bool) BooleanValue {
return &v
}
// True is the BooleanValue equivalent of the Go literal true.
func True() BooleanValue {
return Boolean(true)
}
// False is the BooleanValue equivalent of the Go literal false.
func False() BooleanValue {
return Boolean(false)
}
// An IntegerValue is an integer which may or may not be present.
type IntegerValue *int
// Integer converts a Go int into an IntegerValue.
func Integer(v int) IntegerValue {
return &v
}
// A LongValue is a 64-bit integer which may or may not be present.
type LongValue *int64
// Long converts a Go int64 into a LongValue.
func Long(v int64) LongValue {
return &v
}
// A FloatValue is a 32-bit floating point number which may or may not be
// present.
type FloatValue *float32
// Float converts a Go float32 into a FloatValue.
func Float(v float32) FloatValue {
return &v
}
// A DoubleValue is a 64-bit floating point number which may or may not be
// present.
type DoubleValue *float64
// Double converts a Go float64 into a DoubleValue.
func Double(v float64) DoubleValue {
return &v
}
// A UnixTimestamp is a Unix timestamp represented as fractional seconds since
// the Unix epoch.
type UnixTimestamp struct {
Time time.Time
}
// MarshalJSON marshals the timestamp as a float.
func (t UnixTimestamp) MarshalJSON() (text []byte, err error) {
n := float64(t.Time.UnixNano()) / 1e9
s := strconv.FormatFloat(n, 'f', -1, 64)
return []byte(s), nil
}
// UnmarshalJSON unmarshals the timestamp from a float.
func (t *UnixTimestamp) UnmarshalJSON(text []byte) error {
f, err := strconv.ParseFloat(string(text), 64)
if err != nil {
return err
}
sec := math.Floor(f)
nsec := (f - sec) * 1e9
t.Time = time.Unix(int64(sec), int64(nsec)).UTC()
return nil
}

View file

@ -1,33 +0,0 @@
package aws_test
import (
"encoding/json"
"testing"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
)
func TestUnixTimestampSerialization(t *testing.T) {
d := time.Date(2014, 12, 20, 14, 55, 30, 500000000, time.UTC)
ts := aws.UnixTimestamp{Time: d}
out, err := json.Marshal(ts)
if err != nil {
t.Fatal(err)
}
if v, want := string(out), `1419087330.5`; v != want {
t.Errorf("Was %q but expected %q", v, want)
}
}
func TestUnixTimestampDeserialization(t *testing.T) {
var ts aws.UnixTimestamp
if err := json.Unmarshal([]byte(`1419087330.5`), &ts); err != nil {
t.Fatal(err)
}
if v, want := ts.Time.Format(time.RFC3339Nano), "2014-12-20T14:55:30.5Z"; v != want {
t.Errorf("Was %s but expected %s", v, want)
}
}

View file

@ -1,249 +0,0 @@
package aws
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
const (
authHeaderPrefix = "AWS4-HMAC-SHA256"
timeFormat = "20060102T150405Z"
shortTimeFormat = "20060102"
)
func (c *Context) sign(r *http.Request) error {
creds, err := c.Credentials.Credentials()
if err != nil {
return err
}
date := r.Header.Get("Date")
t := currentTime().UTC()
if date != "" {
var err error
t, err = time.Parse(http.TimeFormat, date)
if err != nil {
return err
}
}
s := signer{
Request: r,
Time: t,
Body: r.Body,
ServiceName: c.Service,
Region: c.Region,
AccessKeyID: creds.AccessKeyID,
SecretAccessKey: creds.SecretAccessKey,
SessionToken: creds.SecurityToken,
Debug: 0,
}
s.sign()
return nil
}
type signer struct {
Request *http.Request
Time time.Time
ServiceName string
Region string
AccessKeyID string
SecretAccessKey string
SessionToken string
Body io.Reader
Debug uint
formattedTime string
formattedShortTime string
signedHeaders string
canonicalHeaders string
canonicalString string
credentialString string
stringToSign string
signature string
authorization string
}
func (v4 *signer) sign() {
formatted := v4.Time.UTC().Format(timeFormat)
// remove the old headers
v4.Request.Header.Del("Date")
v4.Request.Header.Del("Authorization")
if v4.SessionToken != "" {
v4.Request.Header.Set("X-Amz-Security-Token", v4.SessionToken)
}
v4.build()
//v4.Debug = true
if v4.Debug > 0 {
fmt.Printf("---[ CANONICAL STRING ]-----------------------------\n")
fmt.Printf("%s\n", v4.canonicalString)
fmt.Printf("-----------------------------------------------------\n\n")
fmt.Printf("---[ STRING TO SIGN ]--------------------------------\n")
fmt.Printf("%s\n", v4.stringToSign)
fmt.Printf("-----------------------------------------------------\n")
}
// add the new ones
v4.Request.Header.Set("Date", formatted)
v4.Request.Header.Set("Authorization", v4.authorization)
}
func (v4 *signer) build() {
v4.buildTime()
v4.buildCanonicalHeaders()
v4.buildCredentialString()
v4.buildCanonicalString()
v4.buildStringToSign()
v4.buildSignature()
v4.buildAuthorization()
}
func (v4 *signer) buildTime() {
v4.formattedTime = v4.Time.UTC().Format(timeFormat)
v4.formattedShortTime = v4.Time.UTC().Format(shortTimeFormat)
}
func (v4 *signer) buildAuthorization() {
v4.authorization = strings.Join([]string{
authHeaderPrefix + " Credential=" + v4.AccessKeyID + "/" + v4.credentialString,
"SignedHeaders=" + v4.signedHeaders,
"Signature=" + v4.signature,
}, ",")
}
func (v4 *signer) buildCredentialString() {
v4.credentialString = strings.Join([]string{
v4.formattedShortTime,
v4.Region,
v4.ServiceName,
"aws4_request",
}, "/")
}
func (v4 *signer) buildCanonicalHeaders() {
headers := make([]string, 0)
headers = append(headers, "host")
for k, _ := range v4.Request.Header {
if http.CanonicalHeaderKey(k) == "Content-Length" {
continue // never sign content-length
}
headers = append(headers, strings.ToLower(k))
}
sort.Strings(headers)
headerValues := make([]string, len(headers))
for i, k := range headers {
if k == "host" {
headerValues[i] = "host:" + v4.Request.URL.Host
} else {
headerValues[i] = k + ":" +
strings.Join(v4.Request.Header[http.CanonicalHeaderKey(k)], ",")
}
}
v4.signedHeaders = strings.Join(headers, ";")
v4.canonicalHeaders = strings.Join(headerValues, "\n")
}
func (v4 *signer) buildCanonicalString() {
v4.canonicalString = strings.Join([]string{
v4.Request.Method,
v4.Request.URL.Path,
v4.Request.URL.Query().Encode(),
v4.canonicalHeaders + "\n",
v4.signedHeaders,
v4.bodyDigest(),
}, "\n")
}
func (v4 *signer) buildStringToSign() {
v4.stringToSign = strings.Join([]string{
authHeaderPrefix,
v4.formattedTime,
v4.credentialString,
hexDigest(makeSha256([]byte(v4.canonicalString))),
}, "\n")
}
func (v4 *signer) buildSignature() {
secret := v4.SecretAccessKey
date := makeHmac([]byte("AWS4"+secret), []byte(v4.formattedShortTime))
region := makeHmac(date, []byte(v4.Region))
service := makeHmac(region, []byte(v4.ServiceName))
credentials := makeHmac(service, []byte("aws4_request"))
signature := makeHmac(credentials, []byte(v4.stringToSign))
v4.signature = hexDigest(signature)
}
func (v4 *signer) bodyDigest() string {
hash := v4.Request.Header.Get("X-Amz-Content-Sha256")
if hash == "" {
if v4.Body == nil {
hash = hexDigest(makeSha256([]byte{}))
} else {
// TODO refactor body to support seeking body payloads
b, _ := ioutil.ReadAll(v4.Body)
hash = hexDigest(makeSha256(b))
v4.Request.Body = ioutil.NopCloser(bytes.NewReader(b))
}
v4.Request.Header.Add("X-Amz-Content-Sha256", hash)
}
return hash
}
func makeHmac(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
func makeSha256(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
func makeSha256Reader(reader io.Reader) []byte {
packet := make([]byte, 4096)
hash := sha256.New()
//reader.Seek(0, 0)
for {
n, err := reader.Read(packet)
if n > 0 {
hash.Write(packet[0:n])
}
if err == io.EOF || n == 0 {
break
}
}
//reader.Seek(0, 0)
return hash.Sum(nil)
}
func hexDigest(data []byte) string {
var buffer bytes.Buffer
for i := range data {
str := strconv.FormatUint(uint64(data[i]), 16)
if len(str) < 2 {
buffer.WriteString("0")
}
buffer.WriteString(str)
}
return buffer.String()
}

View file

@ -1,64 +0,0 @@
package aws
import (
"net/http"
"strings"
"testing"
"time"
)
func buildSigner(serviceName string, region string, signTime time.Time, body string) signer {
endpoint := "https://" + serviceName + "." + region + ".amazonaws.com"
reader := strings.NewReader(body)
req, _ := http.NewRequest("POST", endpoint, reader)
req.Header.Add("X-Amz-Target", "prefix.Operation")
req.Header.Add("Content-Type", "application/x-amz-json-1.0")
req.Header.Add("Content-Length", string(len(body)))
return signer{
Request: req,
Time: signTime,
Body: reader,
ServiceName: serviceName,
Region: region,
AccessKeyID: "AKID",
SecretAccessKey: "SECRET",
SessionToken: "SESSION",
}
}
func removeWS(text string) string {
text = strings.Replace(text, " ", "", -1)
text = strings.Replace(text, "\n", "", -1)
text = strings.Replace(text, "\t", "", -1)
return text
}
func assertEqual(t *testing.T, expected, given string) {
if removeWS(expected) != removeWS(given) {
t.Errorf("\nExpected: %s\nGiven: %s", expected, given)
}
}
func TestSignRequest(t *testing.T) {
signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), "{}")
signer.sign()
expectedDate := "19700101T000000Z"
expectedAuth := `
AWS4-HMAC-SHA256
Credential=AKID/19700101/us-east-1/dynamodb/aws4_request,
SignedHeaders=content-type;host;x-amz-security-token;x-amz-target,
Signature=4662104789134800e088b6a2bf3a1153ca7d38ecfc07a69bff2859f04900b67f
`
assertEqual(t, expectedAuth, signer.Request.Header.Get("Authorization"))
assertEqual(t, expectedDate, signer.Request.Header.Get("Date"))
}
func BenchmarkSignRequest(b *testing.B) {
signer := buildSigner("dynamodb", "us-east-1", time.Now(), "{}")
for i := 0; i < b.N; i++ {
signer.sign()
}
}

View file

@ -1,178 +0,0 @@
package aws
import (
"encoding/xml"
"reflect"
"strings"
)
// MarshalXML is a weird and stunted version of xml.Marshal which is used by the
// REST-XML request types to get around a bug in encoding/xml which doesn't
// allow us to marshal pointers to zero values:
//
// https://github.com/golang/go/issues/5452
func MarshalXML(v interface{}, e *xml.Encoder, start xml.StartElement) error {
value := reflect.ValueOf(v)
t := value.Type()
switch value.Kind() {
case reflect.Ptr:
if !value.IsNil() {
return MarshalXML(value.Elem().Interface(), e, start)
}
case reflect.Struct:
var rootInfo xmlFieldInfo
// detect xml.Name, if any
for i := 0; i < value.NumField(); i++ {
f := t.Field(i)
v := value.Field(i)
if f.Type == xmlName {
rootInfo = parseXMLTag(f.Tag.Get("xml"))
if rootInfo.name == "" {
// name not in tag, try value
name := v.Interface().(xml.Name)
rootInfo = xmlFieldInfo{
name: name.Local,
ns: name.Space,
}
}
}
}
for _, start := range rootInfo.start(t.Name()) {
if err := e.EncodeToken(start); err != nil {
return err
}
}
for i := 0; i < value.NumField(); i++ {
ft := value.Type().Field(i)
if ft.Type == xmlName {
continue
}
fv := value.Field(i)
fi := parseXMLTag(ft.Tag.Get("xml"))
if fi.name == "-" {
continue
}
if fi.omit {
switch fv.Kind() {
case reflect.Ptr:
if fv.IsNil() {
continue
}
case reflect.Slice, reflect.Map:
if fv.Len() == 0 {
continue
}
default:
if !fv.IsValid() {
continue
}
}
}
starts := fi.start(ft.Name)
for _, start := range starts[:len(starts)-1] {
if err := e.EncodeToken(start); err != nil {
return err
}
}
start := starts[len(starts)-1]
if err := e.EncodeElement(fv.Interface(), start); err != nil {
return err
}
for _, end := range fi.end(ft.Name)[1:] {
if err := e.EncodeToken(end); err != nil {
return err
}
}
}
for _, end := range rootInfo.end(t.Name()) {
if err := e.EncodeToken(end); err != nil {
return err
}
}
default:
return e.Encode(v)
}
return nil
}
var xmlName = reflect.TypeOf(xml.Name{})
type xmlFieldInfo struct {
name string
ns string
omit bool
}
func (fi xmlFieldInfo) start(name string) []xml.StartElement {
if fi.name != "" {
name = fi.name
}
var elements []xml.StartElement
for _, part := range strings.Split(name, ">") {
elements = append(elements, xml.StartElement{
Name: xml.Name{
Local: part,
Space: fi.ns,
},
})
}
return elements
}
func (fi xmlFieldInfo) end(name string) []xml.EndElement {
if fi.name != "" {
name = fi.name
}
var elements []xml.EndElement
parts := strings.Split(name, ">")
for i := range parts {
part := parts[len(parts)-i-1]
elements = append(elements, xml.EndElement{
Name: xml.Name{
Local: part,
Space: fi.ns,
},
})
}
return elements
}
func parseXMLTag(t string) xmlFieldInfo {
parts := strings.Split(t, ",")
var omit bool
for _, p := range parts {
omit = omit || p == "omitempty"
}
var name, ns string
if len(parts) > 0 {
nameParts := strings.Split(parts[0], " ")
if len(nameParts) == 2 {
name = nameParts[1]
ns = nameParts[0]
} else if len(nameParts) == 1 {
name = nameParts[0]
}
}
return xmlFieldInfo{
name: name,
ns: ns,
omit: omit,
}
}

View file

@ -1,35 +0,0 @@
package aws_test
import (
"encoding/xml"
"testing"
"github.com/hashicorp/aws-sdk-go/aws"
)
type XMLRequest struct {
XMLName xml.Name `xml:"http://whatever Request"`
Integer aws.IntegerValue `xml:",omitempty"`
DangerZone string `xml:"-"`
}
func (r *XMLRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(r, e, start)
}
func TestMarshalingXML(t *testing.T) {
r := &XMLRequest{
Integer: aws.Integer(0),
DangerZone: "a zone of danger",
}
out, err := xml.Marshal(r)
if err != nil {
t.Fatal(err)
}
if v, want := string(out), `<Request xmlns="http://whatever"><Integer>0</Integer></Request>`; v != want {
t.Errorf("XML was \n%s\n but expected \n%s", v, want)
}
}

View file

@ -1,178 +0,0 @@
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
// Package endpoints provides lookups for all AWS service endpoints.
package endpoints
import (
"strings"
)
// Lookup returns the endpoint for the given service in the given region plus
// any overrides for the service name and region.
func Lookup(service, region string) (uri, newService, newRegion string) {
if override := findOverride(service, region); override != nil {
return override.uri, override.service, override.region
}
switch service {
case "cloudfront":
if !strings.HasPrefix(region, "cn-") {
return format("https://cloudfront.amazonaws.com", service, region), service, "us-east-1"
}
case "dynamodb":
if region == "local" {
return format("http://localhost:8000", service, region), "dynamodb", "us-east-1"
}
case "elasticmapreduce":
if strings.HasPrefix(region, "cn-") {
return format("https://elasticmapreduce.cn-north-1.amazonaws.com.cn", service, region), service, region
}
if region == "eu-central-1" {
return format("https://elasticmapreduce.eu-central-1.amazonaws.com", service, region), service, region
}
if region == "us-east-1" {
return format("https://elasticmapreduce.us-east-1.amazonaws.com", service, region), service, region
}
if region != "" {
return format("https://{region}.elasticmapreduce.amazonaws.com", service, region), service, region
}
case "iam":
if strings.HasPrefix(region, "cn-") {
return format("https://{service}.cn-north-1.amazonaws.com.cn", service, region), service, region
}
if strings.HasPrefix(region, "us-gov") {
return format("https://{service}.us-gov.amazonaws.com", service, region), service, region
}
return format("https://iam.amazonaws.com", service, region), service, "us-east-1"
case "importexport":
if !strings.HasPrefix(region, "cn-") {
return format("https://importexport.amazonaws.com", service, region), service, region
}
case "rds":
if region == "us-east-1" {
return format("https://rds.amazonaws.com", service, region), service, region
}
case "route53":
if !strings.HasPrefix(region, "cn-") {
return format("https://route53.amazonaws.com", service, region), service, region
}
case "s3":
if region == "us-east-1" || region == "" {
return format("{scheme}://s3.amazonaws.com", service, region), service, "us-east-1"
}
if strings.HasPrefix(region, "cn-") {
return format("{scheme}://{service}.{region}.amazonaws.com.cn", service, region), service, region
}
if region == "us-east-1" || region == "ap-northeast-1" || region == "sa-east-1" || region == "ap-southeast-1" || region == "ap-southeast-2" || region == "us-west-2" || region == "us-west-1" || region == "eu-west-1" || region == "us-gov-west-1" || region == "fips-us-gov-west-1" {
return format("{scheme}://{service}-{region}.amazonaws.com", service, region), service, region
}
if region != "" {
return format("{scheme}://{service}.{region}.amazonaws.com", service, region), service, region
}
case "sdb":
if region == "us-east-1" {
return format("https://sdb.amazonaws.com", service, region), service, region
}
case "sqs":
if region == "us-east-1" {
return format("https://queue.amazonaws.com", service, region), service, region
}
if strings.HasPrefix(region, "cn-") {
return format("https://{region}.queue.amazonaws.com.cn", service, region), service, region
}
if region != "" {
return format("https://{region}.queue.amazonaws.com", service, region), service, region
}
case "sts":
if strings.HasPrefix(region, "cn-") {
return format("{scheme}://{service}.cn-north-1.amazonaws.com.cn", service, region), service, region
}
if strings.HasPrefix(region, "us-gov") {
return format("https://{service}.{region}.amazonaws.com", service, region), service, region
}
return format("https://sts.amazonaws.com", service, region), service, "us-east-1"
}
if strings.HasPrefix(region, "cn-") {
return format("{scheme}://{service}.{region}.amazonaws.com.cn", service, region), service, region
}
if region != "" {
return format("{scheme}://{service}.{region}.amazonaws.com", service, region), service, region
}
panic("unknown endpoint for " + service + " in " + region)
}
// AddOverride overrides the endpoint for a specific service, using either an
// existing region name or a fake one (e.g. "test-1").
//
// This allows developers to use local mock AWS services when they're
// writing tests for their Go code that uses aws-go:
//
// endpoints.AddOverride("EC2", "test-1", "http://localhost:3000")
// // This EC2 client uses the override as service endpoint.
// cli := ec2.New(credentials, "test-1", nil)
func AddOverride(service, region, uri string) {
overrides = append(overrides, override{service, region, uri})
}
func format(uri, service, region string) string {
uri = strings.Replace(uri, "{scheme}", "https", -1)
uri = strings.Replace(uri, "{service}", service, -1)
uri = strings.Replace(uri, "{region}", region, -1)
return uri
}
func findOverride(service, region string) *override {
for _, override := range overrides {
if strings.ToUpper(override.service) == strings.ToUpper(service) &&
override.region == region {
return &override
}
}
return nil
}
type override struct {
service string
region string
uri string
}
var overrides []override

File diff suppressed because it is too large Load diff

View file

@ -9,8 +9,8 @@ import (
"testing"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/ec2"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/vault/logical"
logicaltest "github.com/hashicorp/vault/logical/testing"
"github.com/mitchellh/mapstructure"

View file

@ -3,8 +3,8 @@ package aws
import (
"fmt"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/iam"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/vault/logical"
)

View file

@ -3,8 +3,8 @@ package aws
import (
"fmt"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/iam"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"github.com/mitchellh/mapstructure"

View file

@ -5,8 +5,8 @@ import (
"math/rand"
"time"
"github.com/hashicorp/aws-sdk-go/aws"
"github.com/hashicorp/aws-sdk-go/gen/iam"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)