diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index f6ac610a..06baf4b0 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -5,46 +5,10 @@ "./..." ], "Deps": [ - { - "ImportPath": "github.com/awslabs/aws-sdk-go/aws", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/endpoints", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/query", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/rest", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/restxml", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/internal/signer/v4", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, - { - "ImportPath": "github.com/awslabs/aws-sdk-go/service/s3", - "Rev": "528fdccfb1784861a4a24809328f891336449926" - }, { "ImportPath": "github.com/cheggaaa/pb", "Rev": "bd14546a551971ae7f460e6d6e527c5b56cd38d7" }, - { - "ImportPath": "github.com/clbanning/mxj", - "Rev": "da17de41d4c2e579884683ad838411fac440984d" - }, { "ImportPath": "github.com/dustin/go-humanize", "Rev": "8cc1aaa2d955ee82833337cfb10babc42be6bce6" @@ -77,22 +41,6 @@ { "ImportPath": "github.com/shiena/ansicolor", "Rev": "8368d3b31cf6f2c2464c7a91675342c9a0ac6658" - }, - { - "ImportPath": "github.com/stretchr/objx", - "Rev": "cbeaeb16a013161a98496fad62933b1d21786672" - }, - { - "ImportPath": "github.com/stretchr/testify/assert", - "Rev": "e4ec8152c15fc46bd5056ce65997a07c7d415325" - }, - { - "ImportPath": "github.com/stretchr/testify/mock", - "Rev": "e4ec8152c15fc46bd5056ce65997a07c7d415325" - }, - { - "ImportPath": "github.com/vaughan0/go-ini", - "Rev": "a98ad7ee00ec53921f08832bc06ecf7fd600e6a1" } ] } diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy.go deleted file mode 100644 index a96fd68b..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy.go +++ /dev/null @@ -1,68 +0,0 @@ -package awsutil - -import ( - "io" - "reflect" -) - -// Copy deeply copies a src structure to dst. Useful for copying request and -// response structures. -func Copy(dst, src interface{}) { - rcopy(reflect.ValueOf(dst), reflect.ValueOf(src)) -} - -// CopyOf returns a copy of src while also allocating the memory for dst. -// src must be a pointer type or this operation will fail. -func CopyOf(src interface{}) (dst interface{}) { - dsti := reflect.New(reflect.TypeOf(src).Elem()) - dst = dsti.Interface() - rcopy(dsti, reflect.ValueOf(src)) - return -} - -func rcopy(dst, src reflect.Value) { - if !src.IsValid() { - return - } - - switch src.Kind() { - case reflect.Ptr: - if _, ok := src.Interface().(io.Reader); ok { - if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { - dst.Elem().Set(src) - } else if dst.CanSet() { - dst.Set(src) - } - } else { - e := src.Type().Elem() - if dst.CanSet() { - dst.Set(reflect.New(e)) - } - if src.Elem().IsValid() { - rcopy(dst.Elem(), src.Elem()) - } - } - case reflect.Struct: - dst.Set(reflect.New(src.Type()).Elem()) - for i := 0; i < src.NumField(); i++ { - rcopy(dst.Field(i), src.Field(i)) - } - case reflect.Slice: - 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)) - } - case reflect.Map: - s := reflect.MakeMap(src.Type()) - dst.Set(s) - for _, k := range src.MapKeys() { - v := src.MapIndex(k) - v2 := reflect.New(v.Type()).Elem() - rcopy(v2, v) - dst.SetMapIndex(k, v2) - } - default: - dst.Set(src) - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy_test.go deleted file mode 100644 index 15b7929e..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/copy_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package awsutil_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "testing" - - "github.com/awslabs/aws-sdk-go/aws/awsutil" - "github.com/stretchr/testify/assert" -) - -func ExampleCopy() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Print the result - fmt.Println(awsutil.StringValue(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} - -func TestCopy(t *testing.T) { - type Foo struct { - A int - B []*string - C map[string]*int - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - int1 := 1 - int2 := 2 - f1 := &Foo{ - A: 1, - B: []*string{&str1, &str2}, - C: map[string]*int{ - "A": &int1, - "B": &int2, - }, - } - - // Do the copy - var f2 Foo - awsutil.Copy(&f2, f1) - - // Values are equal - assert.Equal(t, f2.A, f1.A) - assert.Equal(t, f2.B, f1.B) - assert.Equal(t, f2.C, f1.C) - - // But pointers are not! - str3 := "nothello" - int3 := 57 - f2.A = 100 - f2.B[0] = &str3 - f2.C["B"] = &int3 - assert.NotEqual(t, f2.A, f1.A) - assert.NotEqual(t, f2.B, f1.B) - assert.NotEqual(t, f2.C, f1.C) -} - -func TestCopyPrimitive(t *testing.T) { - str := "hello" - var s string - awsutil.Copy(&s, &str) - assert.Equal(t, "hello", s) -} - -func TestCopyNil(t *testing.T) { - var s string - awsutil.Copy(&s, nil) - assert.Equal(t, "", s) -} - -func TestCopyReader(t *testing.T) { - var buf io.Reader = bytes.NewReader([]byte("hello world")) - var r io.Reader - awsutil.Copy(&r, buf) - b, err := ioutil.ReadAll(r) - assert.NoError(t, err) - assert.Equal(t, []byte("hello world"), b) - - // empty bytes because this is not a deep copy - b, err = ioutil.ReadAll(buf) - assert.NoError(t, err) - assert.Equal(t, []byte(""), b) -} - -func ExampleCopyOf() { - type Foo struct { - A int - B []*string - } - - // Create the initial value - str1 := "hello" - str2 := "bye bye" - f1 := &Foo{A: 1, B: []*string{&str1, &str2}} - - // Do the copy - v := awsutil.CopyOf(f1) - var f2 *Foo = v.(*Foo) - - // Print the result - fmt.Println(awsutil.StringValue(f2)) - - // Output: - // { - // A: 1, - // B: ["hello","bye bye"] - // } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value.go deleted file mode 100644 index ce4c5e27..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value.go +++ /dev/null @@ -1,142 +0,0 @@ -package awsutil - -import ( - "reflect" - "regexp" - "strconv" - "strings" -) - -var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) - -func rValuesAtPath(v interface{}, path string, create bool) []reflect.Value { - pathparts := strings.Split(path, "||") - if len(pathparts) > 1 { - for _, pathpart := range pathparts { - vals := rValuesAtPath(v, pathpart, create) - if vals != nil && len(vals) > 0 { - return vals - } - } - return nil - } - - values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} - components := strings.Split(path, ".") - for len(values) > 0 && len(components) > 0 { - var index *int64 - var indexStar bool - c := strings.TrimSpace(components[0]) - if c == "" { // no actual component, illegal syntax - return nil - } else if c != "*" && strings.ToLower(c[0:1]) == c[0:1] { - // TODO normalize case for user - return nil // don't support unexported fields - } - - // parse this component - if m := indexRe.FindStringSubmatch(c); m != nil { - c = m[1] - if m[2] == "" { - index = nil - indexStar = true - } else { - i, _ := strconv.ParseInt(m[2], 10, 32) - index = &i - indexStar = false - } - } - - nextvals := []reflect.Value{} - for _, value := range values { - // pull component name out of struct member - if value.Kind() != reflect.Struct { - continue - } - - if c == "*" { // pull all members - for i := 0; i < value.NumField(); i++ { - if f := reflect.Indirect(value.Field(i)); f.IsValid() { - nextvals = append(nextvals, f) - } - } - continue - } - - value = value.FieldByName(c) - if create && value.Kind() == reflect.Ptr && value.IsNil() { - value.Set(reflect.New(value.Type().Elem())) - value = value.Elem() - } else { - value = reflect.Indirect(value) - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - - if indexStar || index != nil { - nextvals = []reflect.Value{} - for _, value := range values { - value := reflect.Indirect(value) - if value.Kind() != reflect.Slice { - continue - } - - if indexStar { // grab all indices - for i := 0; i < value.Len(); i++ { - idx := reflect.Indirect(value.Index(i)) - if idx.IsValid() { - nextvals = append(nextvals, idx) - } - } - continue - } - - // pull out index - i := int(*index) - if i >= value.Len() { // check out of bounds - if create { - // TODO resize slice - } else { - continue - } - } else if i < 0 { // support negative indexing - i = value.Len() + i - } - value = reflect.Indirect(value.Index(i)) - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - } - - components = components[1:] - } - return values -} - -// ValuesAtPath returns a list of objects at the lexical path inside of a structure -func ValuesAtPath(i interface{}, path string) []interface{} { - if rvals := rValuesAtPath(i, path, false); rvals != nil { - vals := make([]interface{}, len(rvals)) - for i, rval := range rvals { - vals[i] = rval.Interface() - } - return vals - } - return nil -} - -// SetValueAtPath sets an object at the lexical path inside of a structure -func SetValueAtPath(i interface{}, path string, v interface{}) { - if rvals := rValuesAtPath(i, path, true); rvals != nil { - for _, rval := range rvals { - rval.Set(reflect.ValueOf(v)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value_test.go deleted file mode 100644 index f7022968..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/path_value_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package awsutil_test - -import ( - "testing" - - "github.com/awslabs/aws-sdk-go/aws/awsutil" - "github.com/stretchr/testify/assert" -) - -type Struct struct { - A []Struct - a []Struct - B *Struct - D *Struct - C string -} - -var data = Struct{ - A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - a: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, - B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, - C: "initial", -} - -func TestValueAtPathSuccess(t *testing.T) { - assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "C")) - assert.Equal(t, []interface{}{"value1"}, awsutil.ValuesAtPath(data, "A[0].C")) - assert.Equal(t, []interface{}{"value2"}, awsutil.ValuesAtPath(data, "A[1].C")) - assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[2].C")) - assert.Equal(t, []interface{}{"value3"}, awsutil.ValuesAtPath(data, "A[-1].C")) - assert.Equal(t, []interface{}{"value1", "value2", "value3"}, awsutil.ValuesAtPath(data, "A[].C")) - assert.Equal(t, []interface{}{"terminal"}, awsutil.ValuesAtPath(data, "B . B . C")) - assert.Equal(t, []interface{}{"terminal", "terminal2"}, awsutil.ValuesAtPath(data, "B.*.C")) - assert.Equal(t, []interface{}{"initial"}, awsutil.ValuesAtPath(data, "A.D.X || C")) -} - -func TestValueAtPathFailure(t *testing.T) { - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "C.x")) - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, ".x")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "X.Y.Z")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[100].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "A[3].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(data, "B.B.C.Z")) - assert.Equal(t, []interface{}(nil), awsutil.ValuesAtPath(data, "a[-1].C")) - assert.Equal(t, []interface{}{}, awsutil.ValuesAtPath(nil, "A.B.C")) -} - -func TestSetValueAtPathSuccess(t *testing.T) { - var s Struct - awsutil.SetValueAtPath(&s, "C", "test1") - awsutil.SetValueAtPath(&s, "B.B.C", "test2") - awsutil.SetValueAtPath(&s, "B.D.C", "test3") - assert.Equal(t, "test1", s.C) - assert.Equal(t, "test2", s.B.B.C) - assert.Equal(t, "test3", s.B.D.C) - - awsutil.SetValueAtPath(&s, "B.*.C", "test0") - assert.Equal(t, "test0", s.B.B.C) - assert.Equal(t, "test0", s.B.D.C) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/string_value.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/string_value.go deleted file mode 100644 index d24b2a9c..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/awsutil/string_value.go +++ /dev/null @@ -1,97 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "reflect" - "strings" -) - -func StringValue(i interface{}) string { - var buf bytes.Buffer - stringValue(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - stringValue(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - stringValue(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - stringValue(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/config.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/config.go deleted file mode 100644 index 89051d3f..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/config.go +++ /dev/null @@ -1,117 +0,0 @@ -package aws - -import ( - "io" - "net/http" - "os" -) - -const DEFAULT_RETRIES = -1 - -var DefaultConfig = &Config{ - Credentials: DefaultCreds(), - Endpoint: "", - Region: os.Getenv("AWS_REGION"), - DisableSSL: false, - ManualSend: false, - HTTPClient: http.DefaultClient, - LogLevel: 0, - Logger: os.Stdout, - MaxRetries: DEFAULT_RETRIES, - DisableParamValidation: false, - DisableComputeChecksums: false, - S3ForcePathStyle: false, -} - -type Config struct { - Credentials CredentialsProvider - Endpoint string - Region string - DisableSSL bool - ManualSend bool - HTTPClient *http.Client - LogLevel uint - Logger io.Writer - MaxRetries int - DisableParamValidation bool - DisableComputeChecksums bool - S3ForcePathStyle bool -} - -func (c Config) Merge(newcfg *Config) *Config { - cfg := Config{} - - if newcfg != nil && newcfg.Credentials != nil { - cfg.Credentials = newcfg.Credentials - } else { - cfg.Credentials = c.Credentials - } - - if newcfg != nil && newcfg.Endpoint != "" { - cfg.Endpoint = newcfg.Endpoint - } else { - cfg.Endpoint = c.Endpoint - } - - if newcfg != nil && newcfg.Region != "" { - cfg.Region = newcfg.Region - } else { - cfg.Region = c.Region - } - - if newcfg != nil && newcfg.DisableSSL { - cfg.DisableSSL = newcfg.DisableSSL - } else { - cfg.DisableSSL = c.DisableSSL - } - - if newcfg != nil && newcfg.ManualSend { - cfg.ManualSend = newcfg.ManualSend - } else { - cfg.ManualSend = c.ManualSend - } - - if newcfg != nil && newcfg.HTTPClient != nil { - cfg.HTTPClient = newcfg.HTTPClient - } else { - cfg.HTTPClient = c.HTTPClient - } - - if newcfg != nil && newcfg.LogLevel != 0 { - cfg.LogLevel = newcfg.LogLevel - } else { - cfg.LogLevel = c.LogLevel - } - - if newcfg != nil && newcfg.Logger != nil { - cfg.Logger = newcfg.Logger - } else { - cfg.Logger = c.Logger - } - - if newcfg != nil && newcfg.MaxRetries != DEFAULT_RETRIES { - cfg.MaxRetries = newcfg.MaxRetries - } else { - cfg.MaxRetries = c.MaxRetries - } - - if newcfg != nil && newcfg.DisableParamValidation { - cfg.DisableParamValidation = newcfg.DisableParamValidation - } else { - cfg.DisableParamValidation = c.DisableParamValidation - } - - if newcfg != nil && newcfg.DisableComputeChecksums { - cfg.DisableComputeChecksums = newcfg.DisableComputeChecksums - } else { - cfg.DisableComputeChecksums = c.DisableComputeChecksums - } - - if newcfg != nil && newcfg.S3ForcePathStyle { - cfg.S3ForcePathStyle = newcfg.S3ForcePathStyle - } else { - cfg.S3ForcePathStyle = c.S3ForcePathStyle - } - - return &cfg -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials.go deleted file mode 100644 index 09c98a4f..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials.go +++ /dev/null @@ -1,291 +0,0 @@ -package aws - -import ( - "bufio" - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "path/filepath" - "sync" - "time" - - "github.com/vaughan0/go-ini" -) - -var currentTime = time.Now - -// Credentials are used to authenticate and authorize calls that you make to -// AWS. -type Credentials struct { - AccessKeyID string - SecretAccessKey string - SessionToken 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") -) - -type DefaultCredentialsProvider struct { -} - -func (p *DefaultCredentialsProvider) Credentials() (*Credentials, error) { - env, err := EnvCreds() - if err == nil { - return env.Credentials() - } - - profile, err := ProfileCreds("", "", 10*time.Minute) - if err == nil { - profileCreds, err := profile.Credentials() - if err == nil { - return profileCreds, nil - } - } - - return IAMCreds().Credentials() -} - -func DefaultCreds() CredentialsProvider { - return &DefaultCredentialsProvider{} -} - -// 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, sessionToken string) CredentialsProvider { - if accessKeyID != "" && secretAccessKey != "" { - return Creds(accessKeyID, secretAccessKey, sessionToken) - } - - 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, sessionToken string) CredentialsProvider { - return staticCredentialsProvider{ - creds: Credentials{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccessKey, - SessionToken: sessionToken, - }, - } -} - -// 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 == "" { - homeDir := os.Getenv("HOME") // *nix - if homeDir == "" { // Windows - homeDir = os.Getenv("USERPROFILE") - } - if homeDir == "" { - return nil, errors.New("User home directory not found.") - } - - filename = filepath.Join(homeDir, ".aws", "credentials") - } - - if profile == "" { - profile = os.Getenv("AWS_PROFILE") - } - 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) - } - - sessionToken := profile["aws_session_token"] - - p.creds = Credentials{ - AccessKeyID: accessKeyID, - SecretAccessKey: secretAccessKey, - SessionToken: sessionToken, - } - 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("%s listing IAM credentials", err) - } - 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, - SessionToken: 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 -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials_test.go deleted file mode 100644 index a5f57e06..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials_test.go +++ /dev/null @@ -1,265 +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.SessionToken, "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.SessionToken, "token"; v != want { - t.Errorf("SessionToken was %v, but expected %v", v, want) - } -} - -func TestProfileCreds(t *testing.T) { - os.Clearenv() - 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.SessionToken, "token"; v != want { - t.Errorf("SessionToken was %v, but expected %v", v, want) - } -} - -func TestProfileCredsWithAWS_PROFILE(t *testing.T) { - os.Clearenv() - os.Setenv("AWS_PROFILE", "no_token") - 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.SessionToken, ""; v != want { - t.Errorf("SessionToken was %v, but expected %v", v, want) - } -} - -func TestProfileCredsWithoutToken(t *testing.T) { - os.Clearenv() - 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.SessionToken, ""; v != want { - t.Errorf("SessionToken was %v, but expected %v", v, want) - } -} - -func BenchmarkProfileCreds(b *testing.B) { - os.Clearenv() - 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) - } - } - }) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/error.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/error.go deleted file mode 100644 index 08453049..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/error.go +++ /dev/null @@ -1,23 +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 - Code string - Message string - RequestID string -} - -func (e APIError) Error() string { - return e.Code + ": " + e.Message -} - -func Error(e error) *APIError { - if err, ok := e.(*APIError); ok { - return err - } else if err, ok := e.(APIError); ok { - return &err - } else { - return nil - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/example.ini b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/example.ini deleted file mode 100644 index aa2dc506..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/example.ini +++ /dev/null @@ -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 diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions.go deleted file mode 100644 index 38e433e4..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions.go +++ /dev/null @@ -1,85 +0,0 @@ -package aws - -import ( - "fmt" - "io" - "strconv" - "time" -) - -var sleepDelay = func(delay time.Duration) { - time.Sleep(delay) -} - -type lener interface { - Len() int -} - -func BuildContentLength(r *Request) { - if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { - length, _ := strconv.ParseInt(slength, 10, 64) - r.HTTPRequest.ContentLength = length - return - } - - var length int64 - switch body := r.Body.(type) { - case nil: - length = 0 - case lener: - length = int64(body.Len()) - case io.Seeker: - cur, _ := body.Seek(0, 1) - end, _ := body.Seek(0, 2) - body.Seek(cur, 0) // make sure to seek back to original location - length = end - cur - default: - panic("Cannot get length of body, must provide `ContentLength`") - } - - r.HTTPRequest.ContentLength = length - r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) -} - -func UserAgentHandler(r *Request) { - r.HTTPRequest.Header.Set("User-Agent", SDKName+"/"+SDKVersion) -} - -func SendHandler(r *Request) { - r.HTTPResponse, r.Error = r.Service.Config.HTTPClient.Do(r.HTTPRequest) -} - -func ValidateResponseHandler(r *Request) { - if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 400 { - r.Error = &APIError{ - StatusCode: r.HTTPResponse.StatusCode, - Code: "UnknownError", - Message: "unknown error", - } - } - r.Retryable = r.Service.ShouldRetry(r) - r.RetryDelay = r.Service.RetryRules(r) -} - -func AfterRetryHandler(r *Request) { - if r.WillRetry() { - sleepDelay(r.RetryDelay) - - r.RetryCount++ - r.Retryable = false - r.Error = nil - } -} - -var ( - ErrMissingRegion = fmt.Errorf("could not find region configuration.") - ErrMissingEndpoint = fmt.Errorf("`Endpoint' configuration is required for this service.") -) - -func ValidateEndpointHandler(r *Request) { - if r.Service.SigningRegion == "" && r.Service.Config.Region == "" { - r.Error = ErrMissingRegion - } else if r.Service.Endpoint == "" { - r.Error = ErrMissingEndpoint - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions_test.go deleted file mode 100644 index 34d982ea..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handler_functions_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package aws - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestValidateEndpointHandler(t *testing.T) { - os.Clearenv() - svc := NewService(&Config{Region: "us-west-2"}) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBack(ValidateEndpointHandler) - - req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.NoError(t, err) -} - -func TestValidateEndpointHandlerErrorRegion(t *testing.T) { - os.Clearenv() - svc := NewService(nil) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBack(ValidateEndpointHandler) - - req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.Error(t, err) - assert.Equal(t, ErrMissingRegion, err) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers.go deleted file mode 100644 index 9bdbb011..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers.go +++ /dev/null @@ -1,82 +0,0 @@ -package aws - -type Handlers struct { - Validate HandlerList - Build HandlerList - Sign HandlerList - Send HandlerList - ValidateResponse HandlerList - Unmarshal HandlerList - UnmarshalMeta HandlerList - UnmarshalError HandlerList - Retry HandlerList - AfterRetry HandlerList -} - -func (h *Handlers) copy() Handlers { - return Handlers{ - Validate: h.Validate.copy(), - Build: h.Build.copy(), - Sign: h.Sign.copy(), - Send: h.Send.copy(), - ValidateResponse: h.ValidateResponse.copy(), - Unmarshal: h.Unmarshal.copy(), - UnmarshalError: h.UnmarshalError.copy(), - UnmarshalMeta: h.UnmarshalMeta.copy(), - Retry: h.Retry.copy(), - AfterRetry: h.AfterRetry.copy(), - } -} - -// Clear removes callback functions for all handlers -func (h *Handlers) Clear() { - h.Validate.Clear() - h.Build.Clear() - h.Send.Clear() - h.Sign.Clear() - h.Unmarshal.Clear() - h.UnmarshalMeta.Clear() - h.UnmarshalError.Clear() - h.ValidateResponse.Clear() - h.Retry.Clear() - h.AfterRetry.Clear() -} - -// A handler list manages zero or more handlers in a list. -type HandlerList struct { - list []func(*Request) -} - -// copy creates a copy of the handler list. -func (l *HandlerList) copy() HandlerList { - var n HandlerList - n.list = append([]func(*Request){}, l.list...) - return n -} - -// Clear clears the handler list. -func (l *HandlerList) Clear() { - l.list = []func(*Request){} -} - -// Len returns the number of handlers in the list. -func (l *HandlerList) Len() int { - return len(l.list) -} - -// PushBack pushes handlers f to the back of the handler list. -func (l *HandlerList) PushBack(f ...func(*Request)) { - l.list = append(l.list, f...) -} - -// PushFront pushes handlers f to the front of the handler list. -func (l *HandlerList) PushFront(f ...func(*Request)) { - l.list = append(f, l.list...) -} - -// Run executes all handlers in the list with a given request object. -func (l *HandlerList) Run(r *Request) { - for _, f := range l.list { - f(r) - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers_test.go deleted file mode 100644 index 26776f6d..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/handlers_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package aws - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestHandlerList(t *testing.T) { - s := "" - r := &Request{} - l := HandlerList{} - l.PushBack(func(r *Request) { - s += "a" - r.Data = s - }) - l.Run(r) - assert.Equal(t, "a", s) - assert.Equal(t, "a", r.Data) -} - -func TestMultipleHandlers(t *testing.T) { - r := &Request{} - l := HandlerList{} - l.PushBack(func(r *Request) { r.Data = nil }) - l.PushFront(func(r *Request) { r.Data = Boolean(true) }) - l.Run(r) - if r.Data != nil { - t.Error("Expected handler to execute") - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator.go deleted file mode 100644 index e1cb5cea..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator.go +++ /dev/null @@ -1,80 +0,0 @@ -package aws - -import ( - "fmt" - "reflect" - "strings" -) - -func ValidateParameters(r *Request) { - if r.ParamsFilled() { - v := validator{errors: []string{}} - v.validateAny(reflect.ValueOf(r.Params), "") - - if count := len(v.errors); count > 0 { - format := "%d validation errors:\n- %s" - msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- ")) - r.Error = APIError{Code: "InvalidParameter", Message: msg} - } - } -} - -type validator struct { - errors []string -} - -func (v *validator) validateAny(value reflect.Value, path string) { - value = reflect.Indirect(value) - if !value.IsValid() { - return - } - - switch value.Kind() { - case reflect.Struct: - v.validateStruct(value, path) - case reflect.Slice: - for i := 0; i < value.Len(); i++ { - v.validateAny(value.Index(i), path+fmt.Sprintf("[%d]", i)) - } - case reflect.Map: - for _, n := range value.MapKeys() { - v.validateAny(value.MapIndex(n), path+fmt.Sprintf("[%q]", n.String())) - } - } -} - -func (v *validator) validateStruct(value reflect.Value, path string) { - prefix := "." - if path == "" { - prefix = "" - } - - for i := 0; i < value.Type().NumField(); i++ { - f := value.Type().Field(i) - if strings.ToLower(f.Name[0:1]) == f.Name[0:1] { - continue - } - fvalue := value.FieldByName(f.Name) - - notset := false - if f.Tag.Get("required") != "" { - switch fvalue.Kind() { - case reflect.Ptr, reflect.Slice: - if fvalue.IsNil() { - notset = true - } - default: - if !fvalue.IsValid() { - notset = true - } - } - } - - if notset { - msg := "missing required parameter: " + path + prefix + f.Name - v.errors = append(v.errors, msg) - } else { - v.validateAny(fvalue, path+prefix+f.Name) - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator_test.go deleted file mode 100644 index 952f2b28..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/param_validator_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package aws_test - -import ( - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/stretchr/testify/assert" -) - -var service = func() *aws.Service { - s := &aws.Service{ - Config: &aws.Config{}, - ServiceName: "mock-service", - APIVersion: "2015-01-01", - } - return s -}() - -type StructShape struct { - RequiredList []*ConditionalStructShape `required:"true"` - RequiredMap *map[string]*ConditionalStructShape `required:"true"` - RequiredBool *bool `required:"true"` - OptionalStruct *ConditionalStructShape - - hiddenParameter *string - - metadataStructureShape -} - -type metadataStructureShape struct { - SDKShapeTraits bool -} - -type ConditionalStructShape struct { - Name *string `required:"true"` - SDKShapeTraits bool -} - -func TestNoErrors(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{}, - RequiredMap: &map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {Name: aws.String("Name")}, - }, - RequiredBool: aws.Boolean(true), - OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, - } - - req := aws.NewRequest(service, &aws.Operation{}, input, nil) - aws.ValidateParameters(req) - assert.NoError(t, req.Error) -} - -func TestMissingRequiredParameters(t *testing.T) { - input := &StructShape{} - req := aws.NewRequest(service, &aws.Operation{}, input, nil) - aws.ValidateParameters(req) - err := aws.Error(req.Error) - - assert.Error(t, err) - assert.Equal(t, "InvalidParameter", err.Code) - assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", err.Message) -} - -func TestNestedMissingRequiredParameters(t *testing.T) { - input := &StructShape{ - RequiredList: []*ConditionalStructShape{{}}, - RequiredMap: &map[string]*ConditionalStructShape{ - "key1": {Name: aws.String("Name")}, - "key2": {}, - }, - RequiredBool: aws.Boolean(true), - OptionalStruct: &ConditionalStructShape{}, - } - - req := aws.NewRequest(service, &aws.Operation{}, input, nil) - aws.ValidateParameters(req) - err := aws.Error(req.Error) - - assert.Error(t, err) - assert.Equal(t, "InvalidParameter", err.Code) - assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", err.Message) - -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request.go deleted file mode 100644 index b227c0f0..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request.go +++ /dev/null @@ -1,160 +0,0 @@ -package aws - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "time" -) - -type Request struct { - *Service - Handlers Handlers - Time time.Time - ExpireTime time.Duration - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount uint - Retryable bool - RetryDelay time.Duration - - built bool -} - -type Operation struct { - Name string - HTTPMethod string - HTTPPath string -} - -func NewRequest(service *Service, operation *Operation, params interface{}, data interface{}) *Request { - method := operation.HTTPMethod - if method == "" { - method = "POST" - } - p := operation.HTTPPath - if p == "" { - p = "/" - } - - httpReq, _ := http.NewRequest(method, "", nil) - httpReq.URL, _ = url.Parse(service.Endpoint + p) - - r := &Request{ - Service: service, - Handlers: service.Handlers.copy(), - Time: time.Now(), - ExpireTime: 0, - Operation: operation, - HTTPRequest: httpReq, - Body: nil, - Params: params, - Error: nil, - Data: data, - } - r.SetBufferBody([]byte{}) - - return r -} - -func (r *Request) WillRetry() bool { - return r.Error != nil && r.Retryable && r.RetryCount < r.Service.MaxRetries() -} - -func (r *Request) ParamsFilled() bool { - return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() -} - -func (r *Request) DataFilled() bool { - return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid() -} - -func (r *Request) SetBufferBody(buf []byte) { - r.SetReaderBody(bytes.NewReader(buf)) -} - -func (r *Request) SetReaderBody(reader io.ReadSeeker) { - r.HTTPRequest.Body = ioutil.NopCloser(reader) - r.Body = reader -} - -func (r *Request) Presign(expireTime time.Duration) (string, error) { - r.ExpireTime = expireTime - r.Sign() - if r.Error != nil { - return "", r.Error - } else { - return r.HTTPRequest.URL.String(), nil - } -} - -func (r *Request) Build() error { - if !r.built { - r.Error = nil - r.Handlers.Validate.Run(r) - if r.Error != nil { - return r.Error - } - r.Handlers.Build.Run(r) - r.built = true - } - - return r.Error -} - -func (r *Request) Sign() error { - r.Build() - if r.Error != nil { - return r.Error - } - - r.Handlers.Sign.Run(r) - return r.Error -} - -func (r *Request) Send() error { - r.Sign() - if r.Error != nil { - return r.Error - } - - for { - r.Handlers.Send.Run(r) - if r.Error != nil { - return r.Error - } - - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - return r.Error - } - continue - } - - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - return r.Error - } - continue - } - - return nil - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request_test.go deleted file mode 100644 index 11055036..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/request_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package aws - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "reflect" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -type testData struct { - Data string -} - -func body(str string) io.ReadCloser { - return ioutil.NopCloser(bytes.NewReader([]byte(str))) -} - -func unmarshal(req *Request) { - defer req.HTTPResponse.Body.Close() - if req.Data != nil { - json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) - } - return -} - -func unmarshalError(req *Request) { - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = err - return - } - if len(bodyBytes) == 0 { - req.Error = APIError{ - StatusCode: req.HTTPResponse.StatusCode, - Message: req.HTTPResponse.Status, - } - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = err - return - } - req.Error = APIError{ - StatusCode: req.HTTPResponse.StatusCode, - Code: jsonErr.Code, - Message: jsonErr.Message, - } -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} - -func TestRequestRecoverRetry(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := NewService(&Config{MaxRetries: 10}) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := NewRequest(s, &Operation{Name: "Operation"}, nil, out) - err := r.Send() - assert.Nil(t, err) - assert.Equal(t, 2, int(r.RetryCount)) - assert.Equal(t, "valid", out.Data) -} - -func TestRequestExhaustRetries(t *testing.T) { - delays := []time.Duration{} - sleepDelay = func(delay time.Duration) { - delays = append(delays, delay) - } - - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - } - - s := NewService(&Config{MaxRetries: -1}) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := NewRequest(s, &Operation{Name: "Operation"}, nil, nil) - err := r.Send() - apiErr := Error(err) - assert.NotNil(t, err) - assert.NotNil(t, apiErr) - assert.Equal(t, 500, apiErr.StatusCode) - assert.Equal(t, "UnknownError", apiErr.Code) - assert.Equal(t, "An error occurred.", apiErr.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)) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/service.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/service.go deleted file mode 100644 index 0411eb53..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/service.go +++ /dev/null @@ -1,143 +0,0 @@ -package aws - -import ( - "fmt" - "math" - "net/http" - "net/http/httputil" - "regexp" - "time" - - "github.com/awslabs/aws-sdk-go/internal/endpoints" -) - -type Service struct { - Config *Config - Handlers Handlers - ManualSend bool - ServiceName string - APIVersion string - Endpoint string - SigningRegion string - JSONVersion string - TargetPrefix string - RetryRules func(*Request) time.Duration - ShouldRetry func(*Request) bool - DefaultMaxRetries uint -} - -var schemeRE = regexp.MustCompile("^([^:]+)://") - -func NewService(config *Config) *Service { - svc := &Service{Config: config} - svc.Initialize() - return svc -} - -func (s *Service) Initialize() { - if s.Config == nil { - s.Config = &Config{} - } - if s.Config.HTTPClient == nil { - s.Config.HTTPClient = http.DefaultClient - } - - if s.RetryRules == nil { - s.RetryRules = retryRules - } - - if s.ShouldRetry == nil { - s.ShouldRetry = shouldRetry - } - - s.DefaultMaxRetries = 3 - s.Handlers.Validate.PushBack(ValidateEndpointHandler) - s.Handlers.Build.PushBack(UserAgentHandler) - s.Handlers.Sign.PushBack(BuildContentLength) - s.Handlers.Send.PushBack(SendHandler) - s.Handlers.AfterRetry.PushBack(AfterRetryHandler) - s.Handlers.ValidateResponse.PushBack(ValidateResponseHandler) - s.AddDebugHandlers() - s.buildEndpoint() - - if !s.Config.DisableParamValidation { - s.Handlers.Validate.PushBack(ValidateParameters) - } -} - -func (s *Service) buildEndpoint() { - if s.Config.Endpoint != "" { - s.Endpoint = s.Config.Endpoint - } else { - s.Endpoint, s.SigningRegion = - endpoints.EndpointForRegion(s.ServiceName, s.Config.Region) - } - - if s.Endpoint != "" && !schemeRE.MatchString(s.Endpoint) { - scheme := "https" - if s.Config.DisableSSL { - scheme = "http" - } - s.Endpoint = scheme + "://" + s.Endpoint - } -} - -func (s *Service) AddDebugHandlers() { - out := s.Config.Logger - if s.Config.LogLevel == 0 { - return - } - - s.Handlers.Sign.PushBack(func(r *Request) { - dumpedBody, _ := httputil.DumpRequest(r.HTTPRequest, true) - - fmt.Fprintf(out, "=> [%s] %s.%s(%+v)\n", r.Time, - r.Service.ServiceName, r.Operation.Name, r.Params) - fmt.Fprintf(out, "---[ REQUEST PRE-SIGN ]------------------------------\n") - fmt.Fprintf(out, "%s\n", string(dumpedBody)) - fmt.Fprintf(out, "-----------------------------------------------------\n") - }) - s.Handlers.Send.PushFront(func(r *Request) { - dumpedBody, _ := httputil.DumpRequestOut(r.HTTPRequest, true) - - 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 { - dumpedBody, _ := httputil.DumpResponse(r.HTTPResponse, true) - fmt.Fprintf(out, "%s\n", string(dumpedBody)) - } else if r.Error != nil { - fmt.Fprintf(out, "%s\n", r.Error) - } - fmt.Fprintf(out, "-----------------------------------------------------\n") - }) -} - -func (s *Service) MaxRetries() uint { - if s.Config.MaxRetries < 0 { - return s.DefaultMaxRetries - } else { - return uint(s.Config.MaxRetries) - } -} - -func retryRules(r *Request) time.Duration { - delay := time.Duration(math.Pow(2, float64(r.RetryCount))) * 30 - return delay * time.Millisecond -} - -func shouldRetry(r *Request) bool { - if r.HTTPResponse.StatusCode >= 500 { - return true - } else if err := Error(r.Error); err != nil { - switch err.Code { - case "ExpiredTokenException": - case "ProvisionedThroughputExceededException", "Throttling": - return true - } - } - return false -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/types.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/types.go deleted file mode 100644 index 5da09114..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/types.go +++ /dev/null @@ -1,63 +0,0 @@ -package aws - -import ( - "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 -} - -func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { - return ReaderSeekerCloser{r} -} - -type ReaderSeekerCloser struct { - r io.Reader -} - -func (r ReaderSeekerCloser) Read(p []byte) (int, error) { - switch t := r.r.(type) { - case io.Reader: - return t.Read(p) - } - return 0, nil -} - -func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { - switch t := r.r.(type) { - case io.Seeker: - return t.Seek(offset, whence) - } - return int64(0), nil -} - -func (r ReaderSeekerCloser) Close() error { - switch t := r.r.(type) { - case io.Closer: - return t.Close() - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/version.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/version.go deleted file mode 100644 index f673d470..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/version.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -const SDKName = "aws-sdk-go" -const SDKVersion = "0.5.0" diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.go deleted file mode 100644 index 59051011..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.go +++ /dev/null @@ -1,27 +0,0 @@ -package endpoints - -//go:generate go run ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go - -import "strings" - -func EndpointForRegion(svcName, region string) (endpoint, signingRegion string) { - derivedKeys := []string{ - region + "/" + svcName, - region + "/*", - "*/" + svcName, - "*/*", - } - - for _, key := range derivedKeys { - if val, ok := endpointsMap.Endpoints[key]; ok { - ep := val.Endpoint - ep = strings.Replace(ep, "{region}", region, -1) - ep = strings.Replace(ep, "{service}", svcName, -1) - - endpoint = ep - signingRegion = val.SigningRegion - return - } - } - return -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.json b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.json deleted file mode 100644 index 4c588090..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "version": 2, - "endpoints": { - "*/*": { - "endpoint": "{service}.{region}.amazonaws.com" - }, - "cn-north-1/*": { - "endpoint": "{service}.{region}.amazonaws.com.cn", - "signatureVersion": "v4" - }, - "us-gov-west-1/iam": { - "endpoint": "iam.us-gov.amazonaws.com" - }, - "us-gov-west-1/sts": { - "endpoint": "sts.us-gov-west-1.amazonaws.com" - }, - "us-gov-west-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "*/cloudfront": { - "endpoint": "cloudfront.amazonaws.com", - "signingRegion": "us-east-1" - }, - "*/cloudsearchdomain": { - "endpoint": "", - "signingRegion": "us-east-1" - }, - "*/iam": { - "endpoint": "iam.amazonaws.com", - "signingRegion": "us-east-1" - }, - "*/importexport": { - "endpoint": "importexport.amazonaws.com", - "signingRegion": "us-east-1" - }, - "*/route53": { - "endpoint": "route53.amazonaws.com", - "signingRegion": "us-east-1" - }, - "*/sts": { - "endpoint": "sts.amazonaws.com", - "signingRegion": "us-east-1" - }, - "us-east-1/sdb": { - "endpoint": "sdb.amazonaws.com", - "signingRegion": "us-east-1" - }, - "us-east-1/s3": { - "endpoint": "s3.amazonaws.com" - }, - "us-west-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "us-west-2/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "eu-west-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "ap-southeast-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "ap-southeast-2/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "ap-northeast-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "sa-east-1/s3": { - "endpoint": "s3-{region}.amazonaws.com" - }, - "eu-central-1/s3": { - "endpoint": "{service}.{region}.amazonaws.com", - "signatureVersion": "v4" - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_map.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_map.go deleted file mode 100644 index 894c1a64..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_map.go +++ /dev/null @@ -1,89 +0,0 @@ -package endpoints - -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -type endpointStruct struct { - Version int - Endpoints map[string]endpointEntry -} - -type endpointEntry struct { - Endpoint string - SigningRegion string -} - -var endpointsMap = endpointStruct{ - Version: 2, - Endpoints: map[string]endpointEntry{ - "*/*": { - Endpoint: "{service}.{region}.amazonaws.com", - }, - "*/cloudfront": { - Endpoint: "cloudfront.amazonaws.com", - SigningRegion: "us-east-1", - }, - "*/cloudsearchdomain": { - Endpoint: "", - SigningRegion: "us-east-1", - }, - "*/iam": { - Endpoint: "iam.amazonaws.com", - SigningRegion: "us-east-1", - }, - "*/importexport": { - Endpoint: "importexport.amazonaws.com", - SigningRegion: "us-east-1", - }, - "*/route53": { - Endpoint: "route53.amazonaws.com", - SigningRegion: "us-east-1", - }, - "*/sts": { - Endpoint: "sts.amazonaws.com", - SigningRegion: "us-east-1", - }, - "ap-northeast-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "ap-southeast-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "ap-southeast-2/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "cn-north-1/*": { - Endpoint: "{service}.{region}.amazonaws.com.cn", - }, - "eu-central-1/s3": { - Endpoint: "{service}.{region}.amazonaws.com", - }, - "eu-west-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "sa-east-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "us-east-1/s3": { - Endpoint: "s3.amazonaws.com", - }, - "us-east-1/sdb": { - Endpoint: "sdb.amazonaws.com", - SigningRegion: "us-east-1", - }, - "us-gov-west-1/iam": { - Endpoint: "iam.us-gov.amazonaws.com", - }, - "us-gov-west-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "us-gov-west-1/sts": { - Endpoint: "sts.us-gov-west-1.amazonaws.com", - }, - "us-west-1/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - "us-west-2/s3": { - Endpoint: "s3-{region}.amazonaws.com", - }, - }, -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_test.go deleted file mode 100644 index 8af65879..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/endpoints/endpoints_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package endpoints - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGlobalEndpoints(t *testing.T) { - region := "mock-region-1" - svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts"} - - for _, name := range svcs { - ep, sr := EndpointForRegion(name, region) - assert.Equal(t, name+".amazonaws.com", ep) - assert.Equal(t, "us-east-1", sr) - } -} - -func TestServicesInCN(t *testing.T) { - region := "cn-north-1" - svcs := []string{"cloudfront", "iam", "importexport", "route53", "sts", "s3"} - - for _, name := range svcs { - ep, _ := EndpointForRegion(name, region) - assert.Equal(t, name+"."+region+".amazonaws.com.cn", ep) - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build.go deleted file mode 100644 index 74b72165..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build.go +++ /dev/null @@ -1,30 +0,0 @@ -package query - -//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/query.json build_test.go - -import ( - "net/url" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/query/queryutil" -) - -func Build(r *aws.Request) { - body := url.Values{ - "Action": {r.Operation.Name}, - "Version": {r.Service.APIVersion}, - } - if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = err - return - } - - if r.ExpireTime == 0 { - r.HTTPRequest.Method = "POST" - r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - r.SetBufferBody([]byte(body.Encode())) - } else { // This is a pre-signed request - r.HTTPRequest.Method = "GET" - r.HTTPRequest.URL.RawQuery = body.Encode() - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build_test.go deleted file mode 100644 index 48bae0a0..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/build_test.go +++ /dev/null @@ -1,1595 +0,0 @@ -package query_test - -import ( - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/query" - "github.com/awslabs/aws-sdk-go/internal/signer/v4" - - "bytes" - "encoding/json" - "encoding/xml" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/awslabs/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF - -// InputService1ProtocolTest is a client for InputService1ProtocolTest. -type InputService1ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService1ProtocolTest client. -func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice1protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService1ProtocolTest{service} -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - - if opInputService1TestCaseOperation1 == nil { - opInputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(opInputService1TestCaseOperation1, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (output *InputService1TestShapeInputService1TestCaseOperation1Output, err error) { - req, out := c.InputService1TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService1TestCaseOperation1 *aws.Operation - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputShape struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService1TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService1TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService2ProtocolTest is a client for InputService2ProtocolTest. -type InputService2ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService2ProtocolTest client. -func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice2protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService2ProtocolTest{service} -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *aws.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - - if opInputService2TestCaseOperation1 == nil { - opInputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService2TestShapeInputShape{} - } - - req = c.newRequest(opInputService2TestCaseOperation1, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (output *InputService2TestShapeInputService2TestCaseOperation1Output, err error) { - req, out := c.InputService2TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService2TestCaseOperation1 *aws.Operation - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputShape struct { - StructArg *InputService2TestShapeStructType `type:"structure"` - - metadataInputService2TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService2TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeStructType struct { - ScalarArg *string `type:"string"` - - metadataInputService2TestShapeStructType `json:"-", xml:"-"` -} - -type metadataInputService2TestShapeStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService3ProtocolTest is a client for InputService3ProtocolTest. -type InputService3ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService3ProtocolTest client. -func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice3protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService3ProtocolTest{service} -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - - if opInputService3TestCaseOperation1 == nil { - opInputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(opInputService3TestCaseOperation1, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (output *InputService3TestShapeInputService3TestCaseOperation1Output, err error) { - req, out := c.InputService3TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService3TestCaseOperation1 *aws.Operation - -// InputService3TestCaseOperation2Request generates a request for the InputService3TestCaseOperation2 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) { - - if opInputService3TestCaseOperation2 == nil { - opInputService3TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(opInputService3TestCaseOperation2, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *InputService3TestShapeInputShape) (output *InputService3TestShapeInputService3TestCaseOperation2Output, err error) { - req, out := c.InputService3TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService3TestCaseOperation2 *aws.Operation - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation2Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputShape struct { - ListArg []*string `type:"list"` - - metadataInputService3TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService4ProtocolTest is a client for InputService4ProtocolTest. -type InputService4ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService4ProtocolTest client. -func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice4protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService4ProtocolTest{service} -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - - if opInputService4TestCaseOperation1 == nil { - opInputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(opInputService4TestCaseOperation1, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (output *InputService4TestShapeInputService4TestCaseOperation1Output, err error) { - req, out := c.InputService4TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService4TestCaseOperation1 *aws.Operation - -// InputService4TestCaseOperation2Request generates a request for the InputService4TestCaseOperation2 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation2Output) { - - if opInputService4TestCaseOperation2 == nil { - opInputService4TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(opInputService4TestCaseOperation2, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation2(input *InputService4TestShapeInputShape) (output *InputService4TestShapeInputService4TestCaseOperation2Output, err error) { - req, out := c.InputService4TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService4TestCaseOperation2 *aws.Operation - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation2Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputShape struct { - ListArg []*string `type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` - - metadataInputService4TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService5ProtocolTest is a client for InputService5ProtocolTest. -type InputService5ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService5ProtocolTest client. -func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice5protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService5ProtocolTest{service} -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - - if opInputService5TestCaseOperation1 == nil { - opInputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(opInputService5TestCaseOperation1, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (output *InputService5TestShapeInputService5TestCaseOperation1Output, err error) { - req, out := c.InputService5TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService5TestCaseOperation1 *aws.Operation - -// InputService5TestCaseOperation2Request generates a request for the InputService5TestCaseOperation2 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation2Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation2Output) { - - if opInputService5TestCaseOperation2 == nil { - opInputService5TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(opInputService5TestCaseOperation2, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation2(input *InputService5TestShapeInputShape) (output *InputService5TestShapeInputService5TestCaseOperation2Output, err error) { - req, out := c.InputService5TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService5TestCaseOperation2 *aws.Operation - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputService5TestCaseOperation2Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputShape struct { - MapArg *map[string]*string `type:"map"` - - metadataInputService5TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService5TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService6ProtocolTest is a client for InputService6ProtocolTest. -type InputService6ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService6ProtocolTest client. -func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice6protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService6ProtocolTest{service} -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *aws.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - - if opInputService6TestCaseOperation1 == nil { - opInputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService6TestShapeInputShape{} - } - - req = c.newRequest(opInputService6TestCaseOperation1, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (output *InputService6TestShapeInputService6TestCaseOperation1Output, err error) { - req, out := c.InputService6TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService6TestCaseOperation1 *aws.Operation - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputShape struct { - MapArg *map[string]*string `locationNameKey:"TheKey" locationNameValue:"TheValue" type:"map"` - - metadataInputService6TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService6TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService7ProtocolTest is a client for InputService7ProtocolTest. -type InputService7ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService7ProtocolTest client. -func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice7protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService7ProtocolTest{service} -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *aws.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - - if opInputService7TestCaseOperation1 == nil { - opInputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService7TestShapeInputShape{} - } - - req = c.newRequest(opInputService7TestCaseOperation1, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (output *InputService7TestShapeInputService7TestCaseOperation1Output, err error) { - req, out := c.InputService7TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService7TestCaseOperation1 *aws.Operation - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputShape struct { - BlobArg []byte `type:"blob"` - - metadataInputService7TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService7TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService8ProtocolTest is a client for InputService8ProtocolTest. -type InputService8ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService8ProtocolTest client. -func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice8protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService8ProtocolTest{service} -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *aws.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - - if opInputService8TestCaseOperation1 == nil { - opInputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService8TestShapeInputShape{} - } - - req = c.newRequest(opInputService8TestCaseOperation1, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (output *InputService8TestShapeInputService8TestCaseOperation1Output, err error) { - req, out := c.InputService8TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService8TestCaseOperation1 *aws.Operation - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputShape struct { - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService8TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService8TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService9ProtocolTest is a client for InputService9ProtocolTest. -type InputService9ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService9ProtocolTest client. -func NewInputService9ProtocolTest(config *aws.Config) *InputService9ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice9protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &InputService9ProtocolTest{service} -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - - if opInputService9TestCaseOperation1 == nil { - opInputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation1, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation1Output, err error) { - req, out := c.InputService9TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation1 *aws.Operation - -// InputService9TestCaseOperation2Request generates a request for the InputService9TestCaseOperation2 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - - if opInputService9TestCaseOperation2 == nil { - opInputService9TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation2, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation2Output, err error) { - req, out := c.InputService9TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation2 *aws.Operation - -// InputService9TestCaseOperation3Request generates a request for the InputService9TestCaseOperation3 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation3Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation3Output) { - - if opInputService9TestCaseOperation3 == nil { - opInputService9TestCaseOperation3 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation3, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation3Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation3(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation3Output, err error) { - req, out := c.InputService9TestCaseOperation3Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation3 *aws.Operation - -// InputService9TestCaseOperation4Request generates a request for the InputService9TestCaseOperation4 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation4Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation4Output) { - - if opInputService9TestCaseOperation4 == nil { - opInputService9TestCaseOperation4 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation4, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation4Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation4(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation4Output, err error) { - req, out := c.InputService9TestCaseOperation4Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation4 *aws.Operation - -// InputService9TestCaseOperation5Request generates a request for the InputService9TestCaseOperation5 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation5Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation5Output) { - - if opInputService9TestCaseOperation5 == nil { - opInputService9TestCaseOperation5 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation5, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation5Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation5(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation5Output, err error) { - req, out := c.InputService9TestCaseOperation5Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation5 *aws.Operation - -// InputService9TestCaseOperation6Request generates a request for the InputService9TestCaseOperation6 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation6Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation6Output) { - - if opInputService9TestCaseOperation6 == nil { - opInputService9TestCaseOperation6 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation6, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation6Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation6(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation6Output, err error) { - req, out := c.InputService9TestCaseOperation6Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation6 *aws.Operation - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation2Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation3Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation3Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation3Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation4Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation4Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation4Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation5Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation5Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation5Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestCaseOperation6Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation6Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation6Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputService9TestShapeRecursiveStructType struct { - NoRecurse *string `type:"string"` - - RecursiveList []*InputService9TestShapeInputService9TestShapeRecursiveStructType `type:"list"` - - RecursiveMap *map[string]*InputService9TestShapeInputService9TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService9TestShapeInputService9TestShapeRecursiveStructType `type:"structure"` - - metadataInputService9TestShapeInputService9TestShapeRecursiveStructType `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestShapeRecursiveStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputShape struct { - RecursiveStruct *InputService9TestShapeInputService9TestShapeRecursiveStructType `type:"structure"` - - metadataInputService9TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&Bar=val2&Foo=val1&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestNestedStructureMembersCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService2TestShapeInputShape{ - StructArg: &InputService2TestShapeStructType{ - ScalarArg: aws.String("foo"), - }, - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&StructArg.ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - ListArg: []*string{ - aws.String("foo"), - aws.String("bar"), - aws.String("baz"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg.member.1=foo&ListArg.member.2=bar&ListArg.member.3=baz&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestListTypesCase2(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - ListArg: []*string{}, - } - req, _ := svc.InputService3TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg=&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg.1=a&ListArg.2=b&ListArg.3=c&ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestFlattenedListCase2(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - ListArg: []*string{}, - ScalarArg: aws.String("foo"), - } - req, _ := svc.InputService4TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&ListArg=&ScalarArg=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeMapTypeCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - MapArg: &map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&MapArg.entry.1.key=key1&MapArg.entry.1.value=val1&MapArg.entry.2.key=key2&MapArg.entry.2.value=val2&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestSerializeMapTypeCase2(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - MapArg: &map[string]*string{}, - } - req, _ := svc.InputService5TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&MapArg=&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestSerializeMapTypeWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputShape{ - MapArg: &map[string]*string{ - "key1": aws.String("val1"), - "key2": aws.String("val2"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&MapArg.entry.1.TheKey=key1&MapArg.entry.1.TheValue=val1&MapArg.entry.2.TheKey=key2&MapArg.entry.2.TheValue=val2&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputShape{ - BlobArg: []byte("foo"), - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&BlobArg=Zm9v&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestTimestampValuesCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService8TestShapeInputShape{ - TimeArg: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&TimeArg=2015-01-25T08%3A00%3A00Z&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService9TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveStruct.RecursiveStruct.RecursiveStruct.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveList: []*InputService9TestShapeInputService9TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.NoRecurse=bar&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveList: []*InputService9TestShapeInputService9TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveList.member.1.NoRecurse=foo&RecursiveStruct.RecursiveList.member.2.RecursiveStruct.NoRecurse=bar&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - RecursiveStruct: &InputService9TestShapeInputService9TestShapeRecursiveStructType{ - RecursiveMap: &map[string]*InputService9TestShapeInputService9TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService9TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - query.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body, _ := ioutil.ReadAll(r.Body) - assert.Equal(t, util.Trim(`Action=OperationName&RecursiveStruct.RecursiveMap.entry.1.key=bar&RecursiveStruct.RecursiveMap.entry.1.value.NoRecurse=bar&RecursiveStruct.RecursiveMap.entry.2.key=foo&RecursiveStruct.RecursiveMap.entry.2.value.NoRecurse=foo&Version=2014-01-01`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/queryutil/queryutil.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/queryutil/queryutil.go deleted file mode 100644 index 60a13195..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/queryutil/queryutil.go +++ /dev/null @@ -1,221 +0,0 @@ -package queryutil - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -func Parse(body url.Values, i interface{}, isEC2 bool) error { - q := queryParser{isEC2: isEC2} - return q.parseValue(body, reflect.ValueOf(i), "", "") -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type queryParser struct { - isEC2 bool -} - -func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - value = elemOf(value) - - // no need to handle zero values - if !value.IsValid() { - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - return q.parseStruct(v, value, prefix) - case "list": - return q.parseList(v, value, prefix, tag) - case "map": - return q.parseMap(v, value, prefix, tag) - default: - return q.parseScalar(v, value, prefix, tag) - } -} - -func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { - if !value.IsValid() { - return nil - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - value := elemOf(value.Field(i)) - field := t.Field(i) - var name string - - if q.isEC2 { - name = field.Tag.Get("queryName") - } - if name == "" { - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if name != "" && q.isEC2 { - name = strings.ToUpper(name[0:1]) + name[1:] - } - } - if name == "" { - name = field.Name - } - - if prefix != "" { - name = prefix + "." + name - } - - if err := q.parseValue(v, value, name, field.Tag); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".member" - } - - 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 := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".entry" - } - - // sort keys for improved serialization consistency. - // this is not strictly necessary for protocol support. - mapKeyValues := value.MapKeys() - mapKeys := map[string]reflect.Value{} - mapKeyNames := make([]string, len(mapKeyValues)) - for i, mapKey := range mapKeyValues { - name := mapKey.String() - mapKeys[name] = mapKey - mapKeyNames[i] = name - } - sort.Strings(mapKeyNames) - - for i, mapKeyName := range mapKeyNames { - mapKey := mapKeys[mapKeyName] - mapValue := value.MapIndex(mapKey) - - kname := tag.Get("locationNameKey") - if kname == "" { - kname = "key" - } - vname := tag.Get("locationNameValue") - if vname == "" { - vname = "value" - } - - // serialize key - var keyName string - if prefix == "" { - keyName = strconv.Itoa(i+1) + "." + kname - } else { - keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname - } - - if err := q.parseValue(v, mapKey, keyName, ""); err != nil { - return err - } - - // serialize value - var valueName string - if prefix == "" { - valueName = strconv.Itoa(i+1) + "." + vname - } else { - valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname - } - - if err := q.parseValue(v, mapValue, valueName, ""); err != nil { - return err - } - } - - return nil -} - -func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { - switch value := r.Interface().(type) { - case string: - v.Set(name, value) - case []byte: - if !r.IsNil() { - v.Set(name, base64.StdEncoding.EncodeToString(value)) - } - case bool: - v.Set(name, strconv.FormatBool(value)) - case int64: - v.Set(name, strconv.FormatInt(value, 10)) - case int: - v.Set(name, strconv.Itoa(value)) - case float64: - v.Set(name, strconv.FormatFloat(value, 'f', -1, 64)) - case float32: - v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - v.Set(name, value.UTC().Format(ISO8601UTC)) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal.go deleted file mode 100644 index 92a740dc..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal.go +++ /dev/null @@ -1,26 +0,0 @@ -package query - -//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/output/query.json unmarshal_test.go - -import ( - "encoding/xml" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" -) - -func Unmarshal(r *aws.Request) { - defer r.HTTPResponse.Body.Close() - if r.DataFilled() { - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") - if err != nil { - r.Error = err - return - } - } -} - -func UnmarshalMeta(r *aws.Request) { - // TODO implement unmarshaling of request IDs -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_error.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_error.go deleted file mode 100644 index cf82eef9..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_error.go +++ /dev/null @@ -1,31 +0,0 @@ -package query - -import ( - "encoding/xml" - "io" - - "github.com/awslabs/aws-sdk-go/aws" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -func UnmarshalError(r *aws.Request) { - defer r.HTTPResponse.Body.Close() - - resp := &xmlErrorResponse{} - err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) - if err != nil && err != io.EOF { - r.Error = err - } else { - r.Error = aws.APIError{ - StatusCode: r.HTTPResponse.StatusCode, - Code: resp.Code, - Message: resp.Message, - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_test.go deleted file mode 100644 index 3fb843f5..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/query/unmarshal_test.go +++ /dev/null @@ -1,1544 +0,0 @@ -package query_test - -import ( - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/query" - "github.com/awslabs/aws-sdk-go/internal/signer/v4" - - "bytes" - "encoding/json" - "encoding/xml" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/awslabs/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF - -// OutputService1ProtocolTest is a client for OutputService1ProtocolTest. -type OutputService1ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService1ProtocolTest client. -func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice1protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService1ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation1 == nil { - opOutputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService1TestCaseOperation1, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (output *OutputService1TestShapeOutputShape, err error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService1TestCaseOperation1 *aws.Operation - -type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputShape struct { - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - Timestamp *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `type:"boolean"` - - metadataOutputService1TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService1TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService2ProtocolTest is a client for OutputService2ProtocolTest. -type OutputService2ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService2ProtocolTest client. -func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice2protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService2ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *aws.Request, output *OutputService2TestShapeOutputShape) { - - if opOutputService2TestCaseOperation1 == nil { - opOutputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService2TestCaseOperation1, input, output) - output = &OutputService2TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (output *OutputService2TestShapeOutputShape, err error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService2TestCaseOperation1 *aws.Operation - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2TestShapeOutputShape struct { - Num *int64 `type:"integer"` - - Str *string `type:"string"` - - metadataOutputService2TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService2TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService3ProtocolTest is a client for OutputService3ProtocolTest. -type OutputService3ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService3ProtocolTest client. -func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice3protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService3ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *aws.Request, output *OutputService3TestShapeOutputShape) { - - if opOutputService3TestCaseOperation1 == nil { - opOutputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService3TestCaseOperation1, input, output) - output = &OutputService3TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (output *OutputService3TestShapeOutputShape, err error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService3TestCaseOperation1 *aws.Operation - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3TestShapeOutputShape struct { - Blob []byte `type:"blob"` - - metadataOutputService3TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService3TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService4ProtocolTest is a client for OutputService4ProtocolTest. -type OutputService4ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService4ProtocolTest client. -func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice4protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService4ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *aws.Request, output *OutputService4TestShapeOutputShape) { - - if opOutputService4TestCaseOperation1 == nil { - opOutputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService4TestCaseOperation1, input, output) - output = &OutputService4TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (output *OutputService4TestShapeOutputShape, err error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService4TestCaseOperation1 *aws.Operation - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4TestShapeOutputShape struct { - ListMember []*string `type:"list"` - - metadataOutputService4TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService4TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService5ProtocolTest is a client for OutputService5ProtocolTest. -type OutputService5ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService5ProtocolTest client. -func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice5protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService5ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *aws.Request, output *OutputService5TestShapeOutputShape) { - - if opOutputService5TestCaseOperation1 == nil { - opOutputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService5TestCaseOperation1, input, output) - output = &OutputService5TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (output *OutputService5TestShapeOutputShape, err error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService5TestCaseOperation1 *aws.Operation - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5TestShapeOutputShape struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService5TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService5TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService6ProtocolTest is a client for OutputService6ProtocolTest. -type OutputService6ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService6ProtocolTest client. -func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice6protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService6ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *aws.Request, output *OutputService6TestShapeOutputShape) { - - if opOutputService6TestCaseOperation1 == nil { - opOutputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService6TestCaseOperation1, input, output) - output = &OutputService6TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (output *OutputService6TestShapeOutputShape, err error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService6TestCaseOperation1 *aws.Operation - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService6TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService6TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService7ProtocolTest is a client for OutputService7ProtocolTest. -type OutputService7ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService7ProtocolTest client. -func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice7protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService7ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *aws.Request, output *OutputService7TestShapeOutputShape) { - - if opOutputService7TestCaseOperation1 == nil { - opOutputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService7TestCaseOperation1, input, output) - output = &OutputService7TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (output *OutputService7TestShapeOutputShape, err error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService7TestCaseOperation1 *aws.Operation - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService7TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService7TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService8ProtocolTest is a client for OutputService8ProtocolTest. -type OutputService8ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService8ProtocolTest client. -func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice8protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService8ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *aws.Request, output *OutputService8TestShapeOutputShape) { - - if opOutputService8TestCaseOperation1 == nil { - opOutputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService8TestCaseOperation1, input, output) - output = &OutputService8TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (output *OutputService8TestShapeOutputShape, err error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService8TestCaseOperation1 *aws.Operation - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeOutputShape struct { - List []*OutputService8TestShapeStructureShape `type:"list"` - - metadataOutputService8TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService8TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeStructureShape struct { - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` - - metadataOutputService8TestShapeStructureShape `json:"-", xml:"-"` -} - -type metadataOutputService8TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService9ProtocolTest is a client for OutputService9ProtocolTest. -type OutputService9ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService9ProtocolTest client. -func NewOutputService9ProtocolTest(config *aws.Config) *OutputService9ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice9protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService9ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *aws.Request, output *OutputService9TestShapeOutputShape) { - - if opOutputService9TestCaseOperation1 == nil { - opOutputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService9TestCaseOperation1, input, output) - output = &OutputService9TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (output *OutputService9TestShapeOutputShape, err error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService9TestCaseOperation1 *aws.Operation - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeOutputService9TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeOutputShape struct { - List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"` - - metadataOutputService9TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeStructureShape struct { - Bar *string `type:"string"` - - Baz *string `type:"string"` - - Foo *string `type:"string"` - - metadataOutputService9TestShapeStructureShape `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService10ProtocolTest is a client for OutputService10ProtocolTest. -type OutputService10ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService10ProtocolTest client. -func NewOutputService10ProtocolTest(config *aws.Config) *OutputService10ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice10protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService10ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *aws.Request, output *OutputService10TestShapeOutputShape) { - - if opOutputService10TestCaseOperation1 == nil { - opOutputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService10TestCaseOperation1, input, output) - output = &OutputService10TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (output *OutputService10TestShapeOutputShape, err error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService10TestCaseOperation1 *aws.Operation - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService10TestShapeOutputService10TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10TestShapeOutputShape struct { - List []*string `locationNameList:"NamedList" type:"list" flattened:"true"` - - metadataOutputService10TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService10TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService11ProtocolTest is a client for OutputService11ProtocolTest. -type OutputService11ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService11ProtocolTest client. -func NewOutputService11ProtocolTest(config *aws.Config) *OutputService11ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice11protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService11ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *aws.Request, output *OutputService11TestShapeOutputShape) { - - if opOutputService11TestCaseOperation1 == nil { - opOutputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService11TestCaseOperation1, input, output) - output = &OutputService11TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (output *OutputService11TestShapeOutputShape, err error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService11TestCaseOperation1 *aws.Operation - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService11TestShapeOutputService11TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeOutputShape struct { - Map *map[string]*OutputService11TestShapeStructType `type:"map"` - - metadataOutputService11TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService11TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeStructType struct { - Foo *string `locationName:"foo" type:"string"` - - metadataOutputService11TestShapeStructType `json:"-", xml:"-"` -} - -type metadataOutputService11TestShapeStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService12ProtocolTest is a client for OutputService12ProtocolTest. -type OutputService12ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService12ProtocolTest client. -func NewOutputService12ProtocolTest(config *aws.Config) *OutputService12ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice12protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService12ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService12ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *aws.Request, output *OutputService12TestShapeOutputShape) { - - if opOutputService12TestCaseOperation1 == nil { - opOutputService12TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService12TestCaseOperation1, input, output) - output = &OutputService12TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (output *OutputService12TestShapeOutputShape, err error) { - req, out := c.OutputService12TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService12TestCaseOperation1 *aws.Operation - -type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { - metadataOutputService12TestShapeOutputService12TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService12TestShapeOutputService12TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService12TestShapeOutputShape struct { - Map *map[string]*string `type:"map" flattened:"true"` - - metadataOutputService12TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService12TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService13ProtocolTest is a client for OutputService13ProtocolTest. -type OutputService13ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService13ProtocolTest client. -func NewOutputService13ProtocolTest(config *aws.Config) *OutputService13ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice13protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService13ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService13ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService13TestCaseOperation1Request generates a request for the OutputService13TestCaseOperation1 operation. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *aws.Request, output *OutputService13TestShapeOutputShape) { - - if opOutputService13TestCaseOperation1 == nil { - opOutputService13TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService13TestCaseOperation1, input, output) - output = &OutputService13TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (output *OutputService13TestShapeOutputShape, err error) { - req, out := c.OutputService13TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService13TestCaseOperation1 *aws.Operation - -type OutputService13TestShapeOutputService13TestCaseOperation1Input struct { - metadataOutputService13TestShapeOutputService13TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService13TestShapeOutputService13TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService13TestShapeOutputShape struct { - Map *map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` - - metadataOutputService13TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService13TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService14ProtocolTest is a client for OutputService14ProtocolTest. -type OutputService14ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService14ProtocolTest client. -func NewOutputService14ProtocolTest(config *aws.Config) *OutputService14ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice14protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(query.Build) - service.Handlers.Unmarshal.PushBack(query.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(query.UnmarshalError) - - return &OutputService14ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService14ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService14TestCaseOperation1Request generates a request for the OutputService14TestCaseOperation1 operation. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *aws.Request, output *OutputService14TestShapeOutputShape) { - - if opOutputService14TestCaseOperation1 == nil { - opOutputService14TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService14TestCaseOperation1, input, output) - output = &OutputService14TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (output *OutputService14TestShapeOutputShape, err error) { - req, out := c.OutputService14TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService14TestCaseOperation1 *aws.Operation - -type OutputService14TestShapeOutputService14TestCaseOperation1Input struct { - metadataOutputService14TestShapeOutputService14TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService14TestShapeOutputService14TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService14TestShapeOutputShape struct { - Map *map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` - - metadataOutputService14TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService14TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200a2015-01-25T08:00:00Zrequest-id")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "myname", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService2ProtocolTestNotAllMembersInResponseCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(nil) - - buf := bytes.NewReader([]byte("mynamerequest-id")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "myname", *out.Str) - -} - -func TestOutputService3ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(nil) - - buf := bytes.NewReader([]byte("dmFsdWU=requestid")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "value", string(out.Blob)) - -} - -func TestOutputService4ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService5ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService6ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123requestid")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService7ProtocolTestFlattenedSingleElementListCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abcrequestid")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - -} - -func TestOutputService8ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(nil) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "firstbar", *out.List[0].Bar) - assert.Equal(t, "firstbaz", *out.List[0].Baz) - assert.Equal(t, "firstfoo", *out.List[0].Foo) - assert.Equal(t, "secondbar", *out.List[1].Bar) - assert.Equal(t, "secondbaz", *out.List[1].Baz) - assert.Equal(t, "secondfoo", *out.List[1].Foo) - -} - -func TestOutputService9ProtocolTestFlattenedListOfStructuresCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(nil) - - buf := bytes.NewReader([]byte("firstfoofirstbarfirstbazsecondfoosecondbarsecondbazrequestid")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "firstbar", *out.List[0].Bar) - assert.Equal(t, "firstbaz", *out.List[0].Baz) - assert.Equal(t, "firstfoo", *out.List[0].Foo) - assert.Equal(t, "secondbar", *out.List[1].Bar) - assert.Equal(t, "secondbaz", *out.List[1].Baz) - assert.Equal(t, "secondfoo", *out.List[1].Foo) - -} - -func TestOutputService10ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abrequestid")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.List[0]) - assert.Equal(t, "b", *out.List[1]) - -} - -func TestOutputService11ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService11TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"].Foo) - assert.Equal(t, "bar", *(*out.Map)["qux"].Foo) - -} - -func TestOutputService12ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService12ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService12TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"]) - assert.Equal(t, "bar", *(*out.Map)["qux"]) - -} - -func TestOutputService13ProtocolTestFlattenedMapInShapeDefinitionCase1(t *testing.T) { - svc := NewOutputService13ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarrequestid")) - req, out := svc.OutputService13TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bar", *(*out.Map)["qux"]) - -} - -func TestOutputService14ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService14ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbamrequestid")) - req, out := svc.OutputService14TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - query.UnmarshalMeta(req) - query.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"]) - assert.Equal(t, "bar", *(*out.Map)["qux"]) - -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/build.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/build.go deleted file mode 100644 index 3ff667d9..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/build.go +++ /dev/null @@ -1,215 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "time" - - "github.com/awslabs/aws-sdk-go/aws" -) - -// RFC822 returns an RFC822 formatted timestamp for AWS protocols -const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT" - -func Build(r *aws.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v) - buildBody(r, v) - } -} - -func buildLocationElements(r *aws.Request, v reflect.Value) { - query := r.HTTPRequest.URL.Query() - - for i := 0; i < v.NumField(); i++ { - m := v.Field(i) - if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - field := v.Type().Field(i) - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - if m.Kind() == reflect.Ptr { - m = m.Elem() - } - if !m.IsValid() { - continue - } - - switch field.Tag.Get("location") { - case "headers": // header maps - buildHeaderMap(r, m, field.Tag.Get("locationName")) - case "header": - buildHeader(r, m, name) - case "uri": - buildURI(r, m, name) - case "querystring": - buildQueryString(r, m, name, query) - } - } - if r.Error != nil { - return - } - } - - r.HTTPRequest.URL.RawQuery = query.Encode() - updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path) -} - -func buildBody(r *aws.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() && payload.Interface() != nil { - switch reader := payload.Interface().(type) { - case io.ReadSeeker: - r.SetReaderBody(reader) - case []byte: - r.SetBufferBody(reader) - case string: - r.SetBufferBody([]byte(reader)) - default: - r.Error = fmt.Errorf("unknown payload type %s", payload.Type()) - } - } - } - } - } -} - -func buildHeader(r *aws.Request, v reflect.Value, name string) { - str, err := convertType(v) - if err != nil { - r.Error = err - } else if str != nil { - r.HTTPRequest.Header.Add(name, *str) - } -} - -func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) { - for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key)) - - if err != nil { - r.Error = err - } else if str != nil { - r.HTTPRequest.Header.Add(prefix+key.String(), *str) - } - } -} - -func buildURI(r *aws.Request, v reflect.Value, name string) { - value, err := convertType(v) - if err != nil { - r.Error = err - } else if value != nil { - uri := r.HTTPRequest.URL.Path - uri = strings.Replace(uri, "{"+name+"}", escapePath(*value, true), -1) - uri = strings.Replace(uri, "{"+name+"+}", escapePath(*value, false), -1) - r.HTTPRequest.URL.Path = uri - } -} - -func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) { - str, err := convertType(v) - if err != nil { - r.Error = err - } else if str != nil { - query.Set(name, *str) - } -} - -func updatePath(url *url.URL, urlPath string) { - scheme, query := url.Scheme, url.RawQuery - - // clean up path - urlPath = path.Clean(urlPath) - - // get formatted URL minus scheme so we can build this into Opaque - url.Scheme, url.Path, url.RawQuery = "", "", "" - s := url.String() - url.Scheme = scheme - url.RawQuery = query - - // build opaque URI - url.Opaque = s + urlPath -} - -// Whether the byte value can be sent without escaping in AWS URLs -var noEscape [256]bool -var noEscapeInitialized = false - -// initialise noEscape -func initNoEscape() { - 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 == '~' - } -} - -// escapePath escapes part of a URL path in Amazon style -func escapePath(path string, encodeSep bool) string { - if !noEscapeInitialized { - initNoEscape() - noEscapeInitialized = true - } - - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - buf.WriteByte('%') - buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16))) - } - } - return buf.String() -} - -func convertType(v reflect.Value) (*string, error) { - v = reflect.Indirect(v) - if !v.IsValid() { - return nil, nil - } - - var str string - switch value := v.Interface().(type) { - case string: - str = value - case []byte: - str = base64.StdEncoding.EncodeToString(value) - case bool: - str = strconv.FormatBool(value) - case int64: - str = strconv.FormatInt(value, 10) - case float64: - str = strconv.FormatFloat(value, 'f', -1, 64) - case time.Time: - str = value.UTC().Format(RFC822) - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return nil, err - } - return &str, nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/payload.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/payload.go deleted file mode 100644 index 1e15f66f..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/payload.go +++ /dev/null @@ -1,43 +0,0 @@ -package rest - -import "reflect" - -func PayloadMember(i interface{}) interface{} { - if i == nil { - return nil - } - - v := reflect.ValueOf(i).Elem() - if !v.IsValid() { - return nil - } - if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - field, _ := v.Type().FieldByName(payloadName) - if field.Tag.Get("type") != "structure" { - return nil - } - - payload := v.FieldByName(payloadName) - if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { - return payload.Interface() - } - } - } - return nil -} - -func PayloadType(i interface{}) string { - v := reflect.Indirect(reflect.ValueOf(i)) - if !v.IsValid() { - return "" - } - if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - if member, ok := v.Type().FieldByName(payloadName); ok { - return member.Tag.Get("type") - } - } - } - return "" -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/unmarshal.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/unmarshal.go deleted file mode 100644 index d0e216c1..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/rest/unmarshal.go +++ /dev/null @@ -1,174 +0,0 @@ -package rest - -import ( - "encoding/base64" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" - "time" - - "github.com/awslabs/aws-sdk-go/aws" -) - -func Unmarshal(r *aws.Request) { - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalBody(r, v) - unmarshalLocationElements(r, v) - } -} - -func unmarshalBody(r *aws.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() { - switch payload.Interface().(type) { - case []byte: - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = err - } else { - payload.Set(reflect.ValueOf(b)) - } - case string: - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = err - } else { - payload.Set(reflect.ValueOf(string(b))) - } - default: - switch payload.Type().String() { - case "io.ReadSeeker": - payload.Set(reflect.ValueOf(aws.ReadSeekCloser(r.HTTPResponse.Body))) - case "aws.ReadSeekCloser", "io.ReadCloser": - payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) - default: - r.Error = fmt.Errorf("unknown payload type %s", payload.Type()) - } - } - } - } - } - } -} - -func unmarshalLocationElements(r *aws.Request, v reflect.Value) { - for i := 0; i < v.NumField(); i++ { - m, field := v.Field(i), v.Type().Field(i) - if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - - switch field.Tag.Get("location") { - case "statusCode": - unmarshalStatusCode(m, r.HTTPResponse.StatusCode) - case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) - if err != nil { - r.Error = err - break - } - case "headers": - prefix := field.Tag.Get("locationName") - err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) - if err != nil { - r.Error = err - break - } - } - } - if r.Error != nil { - return - } - } -} - -func unmarshalStatusCode(v reflect.Value, statusCode int) { - if !v.IsValid() { - return - } - - switch v.Interface().(type) { - case *int64: - s := int64(statusCode) - v.Set(reflect.ValueOf(&s)) - } -} - -func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { - switch r.Interface().(type) { - case *map[string]*string: // we only support string map value types - out := map[string]*string{} - for k, v := range headers { - k = http.CanonicalHeaderKey(k) - if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { - out[k[len(prefix):]] = &v[0] - } - } - r.Set(reflect.ValueOf(&out)) - } - return nil -} - -func unmarshalHeader(v reflect.Value, header string) error { - if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { - return nil - } - - switch v.Interface().(type) { - case *string: - v.Set(reflect.ValueOf(&header)) - case []byte: - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } else { - v.Set(reflect.ValueOf(&b)) - } - case *bool: - b, err := strconv.ParseBool(header) - if err != nil { - return err - } else { - v.Set(reflect.ValueOf(&b)) - } - case *int64: - i, err := strconv.ParseInt(header, 10, 64) - if err != nil { - return err - } else { - v.Set(reflect.ValueOf(&i)) - } - case *float64: - f, err := strconv.ParseFloat(header, 64) - if err != nil { - return err - } else { - v.Set(reflect.ValueOf(&f)) - } - case *time.Time: - t, err := time.Parse(RFC822, header) - if err != nil { - return err - } else { - v.Set(reflect.ValueOf(&t)) - } - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return err - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/build_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/build_test.go deleted file mode 100644 index 439bbabf..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/build_test.go +++ /dev/null @@ -1,2864 +0,0 @@ -package restxml_test - -import ( - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/restxml" - "github.com/awslabs/aws-sdk-go/internal/signer/v4" - - "bytes" - "encoding/json" - "encoding/xml" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/awslabs/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF - -// InputService1ProtocolTest is a client for InputService1ProtocolTest. -type InputService1ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService1ProtocolTest client. -func NewInputService1ProtocolTest(config *aws.Config) *InputService1ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice1protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService1ProtocolTest{service} -} - -// newRequest creates a new request for a InputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - - if opInputService1TestCaseOperation1 == nil { - opInputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(opInputService1TestCaseOperation1, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputShape) (output *InputService1TestShapeInputService1TestCaseOperation1Output, err error) { - req, out := c.InputService1TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService1TestCaseOperation1 *aws.Operation - -// InputService1TestCaseOperation2Request generates a request for the InputService1TestCaseOperation2 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation2Output) { - - if opInputService1TestCaseOperation2 == nil { - opInputService1TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "PUT", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService1TestShapeInputShape{} - } - - req = c.newRequest(opInputService1TestCaseOperation2, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation2(input *InputService1TestShapeInputShape) (output *InputService1TestShapeInputService1TestCaseOperation2Output, err error) { - req, out := c.InputService1TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService1TestCaseOperation2 *aws.Operation - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation2Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputShape struct { - Description *string `type:"string"` - - Name *string `type:"string"` - - metadataInputService1TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService1TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService2ProtocolTest is a client for InputService2ProtocolTest. -type InputService2ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService2ProtocolTest client. -func NewInputService2ProtocolTest(config *aws.Config) *InputService2ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice2protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService2ProtocolTest{service} -} - -// newRequest creates a new request for a InputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *aws.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - - if opInputService2TestCaseOperation1 == nil { - opInputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService2TestShapeInputShape{} - } - - req = c.newRequest(opInputService2TestCaseOperation1, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputShape) (output *InputService2TestShapeInputService2TestCaseOperation1Output, err error) { - req, out := c.InputService2TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService2TestCaseOperation1 *aws.Operation - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputShape struct { - First *bool `type:"boolean"` - - Fourth *int64 `type:"integer"` - - Second *bool `type:"boolean"` - - Third *float64 `type:"float"` - - metadataInputService2TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService2TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService3ProtocolTest is a client for InputService3ProtocolTest. -type InputService3ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService3ProtocolTest client. -func NewInputService3ProtocolTest(config *aws.Config) *InputService3ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice3protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService3ProtocolTest{service} -} - -// newRequest creates a new request for a InputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - - if opInputService3TestCaseOperation1 == nil { - opInputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService3TestShapeInputShape{} - } - - req = c.newRequest(opInputService3TestCaseOperation1, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputShape) (output *InputService3TestShapeInputService3TestCaseOperation1Output, err error) { - req, out := c.InputService3TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService3TestCaseOperation1 *aws.Operation - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputShape struct { - Description *string `type:"string"` - - SubStructure *InputService3TestShapeSubStructure `type:"structure"` - - metadataInputService3TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService3TestShapeSubStructure struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService3TestShapeSubStructure `json:"-", xml:"-"` -} - -type metadataInputService3TestShapeSubStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService4ProtocolTest is a client for InputService4ProtocolTest. -type InputService4ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService4ProtocolTest client. -func NewInputService4ProtocolTest(config *aws.Config) *InputService4ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice4protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService4ProtocolTest{service} -} - -// newRequest creates a new request for a InputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - - if opInputService4TestCaseOperation1 == nil { - opInputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService4TestShapeInputShape{} - } - - req = c.newRequest(opInputService4TestCaseOperation1, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputShape) (output *InputService4TestShapeInputService4TestCaseOperation1Output, err error) { - req, out := c.InputService4TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService4TestCaseOperation1 *aws.Operation - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputShape struct { - Description *string `type:"string"` - - SubStructure *InputService4TestShapeSubStructure `type:"structure"` - - metadataInputService4TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService4TestShapeSubStructure struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService4TestShapeSubStructure `json:"-", xml:"-"` -} - -type metadataInputService4TestShapeSubStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService5ProtocolTest is a client for InputService5ProtocolTest. -type InputService5ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService5ProtocolTest client. -func NewInputService5ProtocolTest(config *aws.Config) *InputService5ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice5protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService5ProtocolTest{service} -} - -// newRequest creates a new request for a InputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - - if opInputService5TestCaseOperation1 == nil { - opInputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService5TestShapeInputShape{} - } - - req = c.newRequest(opInputService5TestCaseOperation1, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputShape) (output *InputService5TestShapeInputService5TestCaseOperation1Output, err error) { - req, out := c.InputService5TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService5TestCaseOperation1 *aws.Operation - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputShape struct { - ListParam []*string `type:"list"` - - metadataInputService5TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService5TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService6ProtocolTest is a client for InputService6ProtocolTest. -type InputService6ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService6ProtocolTest client. -func NewInputService6ProtocolTest(config *aws.Config) *InputService6ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice6protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService6ProtocolTest{service} -} - -// newRequest creates a new request for a InputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *aws.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - - if opInputService6TestCaseOperation1 == nil { - opInputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService6TestShapeInputShape{} - } - - req = c.newRequest(opInputService6TestCaseOperation1, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputShape) (output *InputService6TestShapeInputService6TestCaseOperation1Output, err error) { - req, out := c.InputService6TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService6TestCaseOperation1 *aws.Operation - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputShape struct { - ListParam []*string `locationName:"AlternateName" locationNameList:"NotMember" type:"list"` - - metadataInputService6TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService6TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService7ProtocolTest is a client for InputService7ProtocolTest. -type InputService7ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService7ProtocolTest client. -func NewInputService7ProtocolTest(config *aws.Config) *InputService7ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice7protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService7ProtocolTest{service} -} - -// newRequest creates a new request for a InputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *aws.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - - if opInputService7TestCaseOperation1 == nil { - opInputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService7TestShapeInputShape{} - } - - req = c.newRequest(opInputService7TestCaseOperation1, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputShape) (output *InputService7TestShapeInputService7TestCaseOperation1Output, err error) { - req, out := c.InputService7TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService7TestCaseOperation1 *aws.Operation - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputShape struct { - ListParam []*string `type:"list" flattened:"true"` - - metadataInputService7TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService7TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService8ProtocolTest is a client for InputService8ProtocolTest. -type InputService8ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService8ProtocolTest client. -func NewInputService8ProtocolTest(config *aws.Config) *InputService8ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice8protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService8ProtocolTest{service} -} - -// newRequest creates a new request for a InputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *aws.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - - if opInputService8TestCaseOperation1 == nil { - opInputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService8TestShapeInputShape{} - } - - req = c.newRequest(opInputService8TestCaseOperation1, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputShape) (output *InputService8TestShapeInputService8TestCaseOperation1Output, err error) { - req, out := c.InputService8TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService8TestCaseOperation1 *aws.Operation - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputShape struct { - ListParam []*string `locationName:"item" type:"list" flattened:"true"` - - metadataInputService8TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService8TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService9ProtocolTest is a client for InputService9ProtocolTest. -type InputService9ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService9ProtocolTest client. -func NewInputService9ProtocolTest(config *aws.Config) *InputService9ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice9protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService9ProtocolTest{service} -} - -// newRequest creates a new request for a InputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - - if opInputService9TestCaseOperation1 == nil { - opInputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService9TestShapeInputShape{} - } - - req = c.newRequest(opInputService9TestCaseOperation1, input, output) - output = &InputService9TestShapeInputService9TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *InputService9TestShapeInputShape) (output *InputService9TestShapeInputService9TestCaseOperation1Output, err error) { - req, out := c.InputService9TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService9TestCaseOperation1 *aws.Operation - -type InputService9TestShapeInputService9TestCaseOperation1Output struct { - metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputService9TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService9TestShapeInputShape struct { - ListParam []*InputService9TestShapeSingleFieldStruct `locationName:"item" type:"list" flattened:"true"` - - metadataInputService9TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService9TestShapeSingleFieldStruct struct { - Element *string `locationName:"value" type:"string"` - - metadataInputService9TestShapeSingleFieldStruct `json:"-", xml:"-"` -} - -type metadataInputService9TestShapeSingleFieldStruct struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService10ProtocolTest is a client for InputService10ProtocolTest. -type InputService10ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService10ProtocolTest client. -func NewInputService10ProtocolTest(config *aws.Config) *InputService10ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice10protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService10ProtocolTest{service} -} - -// newRequest creates a new request for a InputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService10TestCaseOperation1Request generates a request for the InputService10TestCaseOperation1 operation. -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputShape) (req *aws.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - - if opInputService10TestCaseOperation1 == nil { - opInputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } - } - - if input == nil { - input = &InputService10TestShapeInputShape{} - } - - req = c.newRequest(opInputService10TestCaseOperation1, input, output) - output = &InputService10TestShapeInputService10TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *InputService10TestShapeInputShape) (output *InputService10TestShapeInputService10TestCaseOperation1Output, err error) { - req, out := c.InputService10TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService10TestCaseOperation1 *aws.Operation - -type InputService10TestShapeInputService10TestCaseOperation1Output struct { - metadataInputService10TestShapeInputService10TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService10TestShapeInputService10TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService10TestShapeInputShape struct { - StructureParam *InputService10TestShapeStructureShape `type:"structure"` - - metadataInputService10TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService10TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService10TestShapeStructureShape struct { - B []byte `locationName:"b" type:"blob"` - - T *time.Time `locationName:"t" type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService10TestShapeStructureShape `json:"-", xml:"-"` -} - -type metadataInputService10TestShapeStructureShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService11ProtocolTest is a client for InputService11ProtocolTest. -type InputService11ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService11ProtocolTest client. -func NewInputService11ProtocolTest(config *aws.Config) *InputService11ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice11protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService11ProtocolTest{service} -} - -// newRequest creates a new request for a InputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService11TestCaseOperation1Request generates a request for the InputService11TestCaseOperation1 operation. -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputShape) (req *aws.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) { - - if opInputService11TestCaseOperation1 == nil { - opInputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService11TestShapeInputShape{} - } - - req = c.newRequest(opInputService11TestCaseOperation1, input, output) - output = &InputService11TestShapeInputService11TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *InputService11TestShapeInputShape) (output *InputService11TestShapeInputService11TestCaseOperation1Output, err error) { - req, out := c.InputService11TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService11TestCaseOperation1 *aws.Operation - -type InputService11TestShapeInputService11TestCaseOperation1Output struct { - metadataInputService11TestShapeInputService11TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService11TestShapeInputService11TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService11TestShapeInputShape struct { - Foo *map[string]*string `location:"headers" locationName:"x-foo-" type:"map"` - - metadataInputService11TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService11TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -// InputService12ProtocolTest is a client for InputService12ProtocolTest. -type InputService12ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService12ProtocolTest client. -func NewInputService12ProtocolTest(config *aws.Config) *InputService12ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice12protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService12ProtocolTest{service} -} - -// newRequest creates a new request for a InputService12ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService12ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService12TestCaseOperation1Request generates a request for the InputService12TestCaseOperation1 operation. -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1Request(input *InputService12TestShapeInputShape) (req *aws.Request, output *InputService12TestShapeInputService12TestCaseOperation1Output) { - - if opInputService12TestCaseOperation1 == nil { - opInputService12TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService12TestShapeInputShape{} - } - - req = c.newRequest(opInputService12TestCaseOperation1, input, output) - output = &InputService12TestShapeInputService12TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService12ProtocolTest) InputService12TestCaseOperation1(input *InputService12TestShapeInputShape) (output *InputService12TestShapeInputService12TestCaseOperation1Output, err error) { - req, out := c.InputService12TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService12TestCaseOperation1 *aws.Operation - -type InputService12TestShapeInputService12TestCaseOperation1Output struct { - metadataInputService12TestShapeInputService12TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService12TestShapeInputService12TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService12TestShapeInputShape struct { - Foo *string `locationName:"foo" type:"string"` - - metadataInputService12TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService12TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -// InputService13ProtocolTest is a client for InputService13ProtocolTest. -type InputService13ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService13ProtocolTest client. -func NewInputService13ProtocolTest(config *aws.Config) *InputService13ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice13protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService13ProtocolTest{service} -} - -// newRequest creates a new request for a InputService13ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService13ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService13TestCaseOperation1Request generates a request for the InputService13TestCaseOperation1 operation. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1Request(input *InputService13TestShapeInputShape) (req *aws.Request, output *InputService13TestShapeInputService13TestCaseOperation1Output) { - - if opInputService13TestCaseOperation1 == nil { - opInputService13TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService13TestShapeInputShape{} - } - - req = c.newRequest(opInputService13TestCaseOperation1, input, output) - output = &InputService13TestShapeInputService13TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService13ProtocolTest) InputService13TestCaseOperation1(input *InputService13TestShapeInputShape) (output *InputService13TestShapeInputService13TestCaseOperation1Output, err error) { - req, out := c.InputService13TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService13TestCaseOperation1 *aws.Operation - -// InputService13TestCaseOperation2Request generates a request for the InputService13TestCaseOperation2 operation. -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2Request(input *InputService13TestShapeInputShape) (req *aws.Request, output *InputService13TestShapeInputService13TestCaseOperation2Output) { - - if opInputService13TestCaseOperation2 == nil { - opInputService13TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService13TestShapeInputShape{} - } - - req = c.newRequest(opInputService13TestCaseOperation2, input, output) - output = &InputService13TestShapeInputService13TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService13ProtocolTest) InputService13TestCaseOperation2(input *InputService13TestShapeInputShape) (output *InputService13TestShapeInputService13TestCaseOperation2Output, err error) { - req, out := c.InputService13TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService13TestCaseOperation2 *aws.Operation - -type InputService13TestShapeInputService13TestCaseOperation1Output struct { - metadataInputService13TestShapeInputService13TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService13TestShapeInputService13TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService13TestShapeInputService13TestCaseOperation2Output struct { - metadataInputService13TestShapeInputService13TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService13TestShapeInputService13TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService13TestShapeInputShape struct { - Foo []byte `locationName:"foo" type:"blob"` - - metadataInputService13TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService13TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -// InputService14ProtocolTest is a client for InputService14ProtocolTest. -type InputService14ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService14ProtocolTest client. -func NewInputService14ProtocolTest(config *aws.Config) *InputService14ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice14protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService14ProtocolTest{service} -} - -// newRequest creates a new request for a InputService14ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService14ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService14TestCaseOperation1Request generates a request for the InputService14TestCaseOperation1 operation. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1Request(input *InputService14TestShapeInputShape) (req *aws.Request, output *InputService14TestShapeInputService14TestCaseOperation1Output) { - - if opInputService14TestCaseOperation1 == nil { - opInputService14TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService14TestShapeInputShape{} - } - - req = c.newRequest(opInputService14TestCaseOperation1, input, output) - output = &InputService14TestShapeInputService14TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService14ProtocolTest) InputService14TestCaseOperation1(input *InputService14TestShapeInputShape) (output *InputService14TestShapeInputService14TestCaseOperation1Output, err error) { - req, out := c.InputService14TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService14TestCaseOperation1 *aws.Operation - -// InputService14TestCaseOperation2Request generates a request for the InputService14TestCaseOperation2 operation. -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2Request(input *InputService14TestShapeInputShape) (req *aws.Request, output *InputService14TestShapeInputService14TestCaseOperation2Output) { - - if opInputService14TestCaseOperation2 == nil { - opInputService14TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService14TestShapeInputShape{} - } - - req = c.newRequest(opInputService14TestCaseOperation2, input, output) - output = &InputService14TestShapeInputService14TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService14ProtocolTest) InputService14TestCaseOperation2(input *InputService14TestShapeInputShape) (output *InputService14TestShapeInputService14TestCaseOperation2Output, err error) { - req, out := c.InputService14TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService14TestCaseOperation2 *aws.Operation - -type InputService14TestShapeFooShape struct { - Baz *string `locationName:"baz" type:"string"` - - metadataInputService14TestShapeFooShape `json:"-", xml:"-"` -} - -type metadataInputService14TestShapeFooShape struct { - SDKShapeTraits bool `locationName:"foo" type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation1Output struct { - metadataInputService14TestShapeInputService14TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService14TestShapeInputService14TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService14TestShapeInputService14TestCaseOperation2Output struct { - metadataInputService14TestShapeInputService14TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService14TestShapeInputService14TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService14TestShapeInputShape struct { - Foo *InputService14TestShapeFooShape `locationName:"foo" type:"structure"` - - metadataInputService14TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService14TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Foo"` -} - -// InputService15ProtocolTest is a client for InputService15ProtocolTest. -type InputService15ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService15ProtocolTest client. -func NewInputService15ProtocolTest(config *aws.Config) *InputService15ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice15protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService15ProtocolTest{service} -} - -// newRequest creates a new request for a InputService15ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService15ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService15TestCaseOperation1Request generates a request for the InputService15TestCaseOperation1 operation. -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1Request(input *InputService15TestShapeInputShape) (req *aws.Request, output *InputService15TestShapeInputService15TestCaseOperation1Output) { - - if opInputService15TestCaseOperation1 == nil { - opInputService15TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } - } - - if input == nil { - input = &InputService15TestShapeInputShape{} - } - - req = c.newRequest(opInputService15TestCaseOperation1, input, output) - output = &InputService15TestShapeInputService15TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService15ProtocolTest) InputService15TestCaseOperation1(input *InputService15TestShapeInputShape) (output *InputService15TestShapeInputService15TestCaseOperation1Output, err error) { - req, out := c.InputService15TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService15TestCaseOperation1 *aws.Operation - -type InputService15TestShapeGrant struct { - Grantee *InputService15TestShapeGrantee `type:"structure"` - - metadataInputService15TestShapeGrant `json:"-", xml:"-"` -} - -type metadataInputService15TestShapeGrant struct { - SDKShapeTraits bool `locationName:"Grant" type:"structure"` -} - -type InputService15TestShapeGrantee struct { - EmailAddress *string `type:"string"` - - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true"` - - metadataInputService15TestShapeGrantee `json:"-", xml:"-"` -} - -type metadataInputService15TestShapeGrantee struct { - SDKShapeTraits bool `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` -} - -type InputService15TestShapeInputService15TestCaseOperation1Output struct { - metadataInputService15TestShapeInputService15TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService15TestShapeInputService15TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService15TestShapeInputShape struct { - Grant *InputService15TestShapeGrant `locationName:"Grant" type:"structure"` - - metadataInputService15TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService15TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Grant"` -} - -// InputService16ProtocolTest is a client for InputService16ProtocolTest. -type InputService16ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService16ProtocolTest client. -func NewInputService16ProtocolTest(config *aws.Config) *InputService16ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice16protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService16ProtocolTest{service} -} - -// newRequest creates a new request for a InputService16ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService16ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService16TestCaseOperation1Request generates a request for the InputService16TestCaseOperation1 operation. -func (c *InputService16ProtocolTest) InputService16TestCaseOperation1Request(input *InputService16TestShapeInputShape) (req *aws.Request, output *InputService16TestShapeInputService16TestCaseOperation1Output) { - - if opInputService16TestCaseOperation1 == nil { - opInputService16TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &InputService16TestShapeInputShape{} - } - - req = c.newRequest(opInputService16TestCaseOperation1, input, output) - output = &InputService16TestShapeInputService16TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService16ProtocolTest) InputService16TestCaseOperation1(input *InputService16TestShapeInputShape) (output *InputService16TestShapeInputService16TestCaseOperation1Output, err error) { - req, out := c.InputService16TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService16TestCaseOperation1 *aws.Operation - -type InputService16TestShapeInputService16TestCaseOperation1Output struct { - metadataInputService16TestShapeInputService16TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService16TestShapeInputService16TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService16TestShapeInputShape struct { - Bucket *string `location:"uri" type:"string"` - - Key *string `location:"uri" type:"string"` - - metadataInputService16TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService16TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService17ProtocolTest is a client for InputService17ProtocolTest. -type InputService17ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService17ProtocolTest client. -func NewInputService17ProtocolTest(config *aws.Config) *InputService17ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice17protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService17ProtocolTest{service} -} - -// newRequest creates a new request for a InputService17ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService17ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService17TestCaseOperation1Request generates a request for the InputService17TestCaseOperation1 operation. -func (c *InputService17ProtocolTest) InputService17TestCaseOperation1Request(input *InputService17TestShapeInputShape) (req *aws.Request, output *InputService17TestShapeInputService17TestCaseOperation1Output) { - - if opInputService17TestCaseOperation1 == nil { - opInputService17TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService17TestShapeInputShape{} - } - - req = c.newRequest(opInputService17TestCaseOperation1, input, output) - output = &InputService17TestShapeInputService17TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService17ProtocolTest) InputService17TestCaseOperation1(input *InputService17TestShapeInputShape) (output *InputService17TestShapeInputService17TestCaseOperation1Output, err error) { - req, out := c.InputService17TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService17TestCaseOperation1 *aws.Operation - -// InputService17TestCaseOperation2Request generates a request for the InputService17TestCaseOperation2 operation. -func (c *InputService17ProtocolTest) InputService17TestCaseOperation2Request(input *InputService17TestShapeInputShape) (req *aws.Request, output *InputService17TestShapeInputService17TestCaseOperation2Output) { - - if opInputService17TestCaseOperation2 == nil { - opInputService17TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path?abc=mno", - } - } - - if input == nil { - input = &InputService17TestShapeInputShape{} - } - - req = c.newRequest(opInputService17TestCaseOperation2, input, output) - output = &InputService17TestShapeInputService17TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService17ProtocolTest) InputService17TestCaseOperation2(input *InputService17TestShapeInputShape) (output *InputService17TestShapeInputService17TestCaseOperation2Output, err error) { - req, out := c.InputService17TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService17TestCaseOperation2 *aws.Operation - -type InputService17TestShapeInputService17TestCaseOperation1Output struct { - metadataInputService17TestShapeInputService17TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService17TestShapeInputService17TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService17TestShapeInputService17TestCaseOperation2Output struct { - metadataInputService17TestShapeInputService17TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService17TestShapeInputService17TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService17TestShapeInputShape struct { - Foo *string `location:"querystring" locationName:"param-name" type:"string"` - - metadataInputService17TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService17TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService18ProtocolTest is a client for InputService18ProtocolTest. -type InputService18ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService18ProtocolTest client. -func NewInputService18ProtocolTest(config *aws.Config) *InputService18ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice18protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService18ProtocolTest{service} -} - -// newRequest creates a new request for a InputService18ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService18ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService18TestCaseOperation1Request generates a request for the InputService18TestCaseOperation1 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation1Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation1Output) { - - if opInputService18TestCaseOperation1 == nil { - opInputService18TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation1, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation1(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestCaseOperation1Output, err error) { - req, out := c.InputService18TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation1 *aws.Operation - -// InputService18TestCaseOperation2Request generates a request for the InputService18TestCaseOperation2 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation2Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation2Output) { - - if opInputService18TestCaseOperation2 == nil { - opInputService18TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation2, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation2Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation2(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestCaseOperation2Output, err error) { - req, out := c.InputService18TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation2 *aws.Operation - -// InputService18TestCaseOperation3Request generates a request for the InputService18TestCaseOperation3 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation3Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output) { - - if opInputService18TestCaseOperation3 == nil { - opInputService18TestCaseOperation3 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation3, input, output) - output = &InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation3(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output, err error) { - req, out := c.InputService18TestCaseOperation3Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation3 *aws.Operation - -// InputService18TestCaseOperation4Request generates a request for the InputService18TestCaseOperation4 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation4Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output) { - - if opInputService18TestCaseOperation4 == nil { - opInputService18TestCaseOperation4 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation4, input, output) - output = &InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation4(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output, err error) { - req, out := c.InputService18TestCaseOperation4Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation4 *aws.Operation - -// InputService18TestCaseOperation5Request generates a request for the InputService18TestCaseOperation5 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation5Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation5Output) { - - if opInputService18TestCaseOperation5 == nil { - opInputService18TestCaseOperation5 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation5, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation5Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation5(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestCaseOperation5Output, err error) { - req, out := c.InputService18TestCaseOperation5Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation5 *aws.Operation - -// InputService18TestCaseOperation6Request generates a request for the InputService18TestCaseOperation6 operation. -func (c *InputService18ProtocolTest) InputService18TestCaseOperation6Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation6Output) { - - if opInputService18TestCaseOperation6 == nil { - opInputService18TestCaseOperation6 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService18TestShapeInputShape{} - } - - req = c.newRequest(opInputService18TestCaseOperation6, input, output) - output = &InputService18TestShapeInputService18TestCaseOperation6Output{} - req.Data = output - return -} - -func (c *InputService18ProtocolTest) InputService18TestCaseOperation6(input *InputService18TestShapeInputShape) (output *InputService18TestShapeInputService18TestCaseOperation6Output, err error) { - req, out := c.InputService18TestCaseOperation6Request(input) - output = out - err = req.Send() - return -} - -var opInputService18TestCaseOperation6 *aws.Operation - -type InputService18TestShapeInputService18TestCaseOperation1Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation2Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation2Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation2Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation5Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation5Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation5Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestCaseOperation6Output struct { - metadataInputService18TestShapeInputService18TestCaseOperation6Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestCaseOperation6Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output struct { - metadataInputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestShapeInputService18TestCaseOperation3Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output struct { - metadataInputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputService18TestShapeInputService18TestCaseOperation4Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService18TestShapeInputShape struct { - RecursiveStruct *InputService18TestShapeRecursiveStructType `type:"structure"` - - metadataInputService18TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeInputShape struct { - SDKShapeTraits bool `locationName:"OperationRequest" type:"structure" xmlURI:"https://foo/"` -} - -type InputService18TestShapeRecursiveStructType struct { - NoRecurse *string `type:"string"` - - RecursiveList []*InputService18TestShapeRecursiveStructType `type:"list"` - - RecursiveMap *map[string]*InputService18TestShapeRecursiveStructType `type:"map"` - - RecursiveStruct *InputService18TestShapeRecursiveStructType `type:"structure"` - - metadataInputService18TestShapeRecursiveStructType `json:"-", xml:"-"` -} - -type metadataInputService18TestShapeRecursiveStructType struct { - SDKShapeTraits bool `type:"structure"` -} - -// InputService19ProtocolTest is a client for InputService19ProtocolTest. -type InputService19ProtocolTest struct { - *aws.Service -} - -// New returns a new InputService19ProtocolTest client. -func NewInputService19ProtocolTest(config *aws.Config) *InputService19ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "inputservice19protocoltest", - APIVersion: "2014-01-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &InputService19ProtocolTest{service} -} - -// newRequest creates a new request for a InputService19ProtocolTest operation and runs any -// custom request initialization. -func (c *InputService19ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// InputService19TestCaseOperation1Request generates a request for the InputService19TestCaseOperation1 operation. -func (c *InputService19ProtocolTest) InputService19TestCaseOperation1Request(input *InputService19TestShapeInputShape) (req *aws.Request, output *InputService19TestShapeInputService19TestCaseOperation1Output) { - - if opInputService19TestCaseOperation1 == nil { - opInputService19TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } - } - - if input == nil { - input = &InputService19TestShapeInputShape{} - } - - req = c.newRequest(opInputService19TestCaseOperation1, input, output) - output = &InputService19TestShapeInputService19TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService19ProtocolTest) InputService19TestCaseOperation1(input *InputService19TestShapeInputShape) (output *InputService19TestShapeInputService19TestCaseOperation1Output, err error) { - req, out := c.InputService19TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opInputService19TestCaseOperation1 *aws.Operation - -type InputService19TestShapeInputService19TestCaseOperation1Output struct { - metadataInputService19TestShapeInputService19TestCaseOperation1Output `json:"-", xml:"-"` -} - -type metadataInputService19TestShapeInputService19TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService19TestShapeInputShape struct { - TimeArgInHeader *time.Time `location:"header" locationName:"x-amz-timearg" type:"timestamp" timestampFormat:"rfc822"` - - metadataInputService19TestShapeInputShape `json:"-", xml:"-"` -} - -type metadataInputService19TestShapeInputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestBasicXMLSerializationCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Description: aws.String("bar"), - Name: aws.String("foo"), - } - req, _ := svc.InputService1TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barfoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService1ProtocolTestBasicXMLSerializationCase2(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputShape{ - Description: aws.String("bar"), - Name: aws.String("foo"), - } - req, _ := svc.InputService1TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barfoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService2ProtocolTestSerializeOtherScalarTypesCase1(t *testing.T) { - svc := NewInputService2ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService2TestShapeInputShape{ - First: aws.Boolean(true), - Fourth: aws.Long(3), - Second: aws.Boolean(false), - Third: aws.Double(1.2), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`true3false1.2`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService3ProtocolTestNestedStructuresCase1(t *testing.T) { - svc := NewInputService3ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService3TestShapeInputShape{ - Description: aws.String("baz"), - SubStructure: &InputService3TestShapeSubStructure{ - Bar: aws.String("b"), - Foo: aws.String("a"), - }, - } - req, _ := svc.InputService3TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bazba`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService4ProtocolTestNestedStructuresCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputShape{ - Description: aws.String("baz"), - SubStructure: &InputService4TestShapeSubStructure{}, - } - req, _ := svc.InputService4TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`baz`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService5ProtocolTestNonFlattenedListsCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService5TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService6ProtocolTestNonFlattenedListsWithLocationNameCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService6TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService7ProtocolTestFlattenedListsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService7TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService8ProtocolTestFlattenedListsWithLocationNameCase1(t *testing.T) { - svc := NewInputService8ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService8TestShapeInputShape{ - ListParam: []*string{ - aws.String("one"), - aws.String("two"), - aws.String("three"), - }, - } - req, _ := svc.InputService8TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService9ProtocolTestListOfStructuresCase1(t *testing.T) { - svc := NewInputService9ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService9TestShapeInputShape{ - ListParam: []*InputService9TestShapeSingleFieldStruct{ - { - Element: aws.String("one"), - }, - { - Element: aws.String("two"), - }, - { - Element: aws.String("three"), - }, - }, - } - req, _ := svc.InputService9TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`onetwothree`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService10ProtocolTestBlobAndTimestampShapesCase1(t *testing.T) { - svc := NewInputService10ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService10TestShapeInputShape{ - StructureParam: &InputService10TestShapeStructureShape{ - B: []byte("foo"), - T: aws.Time(time.Unix(1422172800, 0)), - }, - } - req, _ := svc.InputService10TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`Zm9v2015-01-25T08:00:00Z`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/2014-01-01/hostedzone", r.URL.String()) - - // assert headers - -} - -func TestInputService11ProtocolTestHeaderMapsCase1(t *testing.T) { - svc := NewInputService11ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService11TestShapeInputShape{ - Foo: &map[string]*string{ - "a": aws.String("b"), - "c": aws.String("d"), - }, - } - req, _ := svc.InputService11TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - assert.Equal(t, "b", r.Header.Get("x-foo-a")) - assert.Equal(t, "d", r.Header.Get("x-foo-c")) - -} - -func TestInputService12ProtocolTestStringPayloadCase1(t *testing.T) { - svc := NewInputService12ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService12TestShapeInputShape{ - Foo: aws.String("bar"), - } - req, _ := svc.InputService12TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestBlobPayloadCase1(t *testing.T) { - svc := NewInputService13ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService13TestShapeInputShape{ - Foo: []byte("bar"), - } - req, _ := svc.InputService13TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService13ProtocolTestBlobPayloadCase2(t *testing.T) { - svc := NewInputService13ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService13TestShapeInputShape{} - req, _ := svc.InputService13TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestStructurePayloadCase1(t *testing.T) { - svc := NewInputService14ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService14TestShapeInputShape{ - Foo: &InputService14TestShapeFooShape{ - Baz: aws.String("bar"), - }, - } - req, _ := svc.InputService14TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`bar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService14ProtocolTestStructurePayloadCase2(t *testing.T) { - svc := NewInputService14ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService14TestShapeInputShape{} - req, _ := svc.InputService14TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService15ProtocolTestXMLAttributeCase1(t *testing.T) { - svc := NewInputService15ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService15TestShapeInputShape{ - Grant: &InputService15TestShapeGrant{ - Grantee: &InputService15TestShapeGrantee{ - EmailAddress: aws.String("foo@example.com"), - Type: aws.String("CanonicalUser"), - }, - }, - } - req, _ := svc.InputService15TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo@example.com`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/", r.URL.String()) - - // assert headers - -} - -func TestInputService16ProtocolTestGreedyKeysCase1(t *testing.T) { - svc := NewInputService16ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService16TestShapeInputShape{ - Bucket: aws.String("my/bucket"), - Key: aws.String("testing /123"), - } - req, _ := svc.InputService16TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/my%2Fbucket/testing%20/123", r.URL.String()) - - // assert headers - -} - -func TestInputService17ProtocolTestOmitsNullQueryParamsButSerializesEmptyStringsCase1(t *testing.T) { - svc := NewInputService17ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService17TestShapeInputShape{} - req, _ := svc.InputService17TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService17ProtocolTestOmitsNullQueryParamsButSerializesEmptyStringsCase2(t *testing.T) { - svc := NewInputService17ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService17TestShapeInputShape{ - Foo: aws.String(""), - } - req, _ := svc.InputService17TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path?abc=mno¶m-name=", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase1(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - } - req, _ := svc.InputService18TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase2(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - } - req, _ := svc.InputService18TestCaseOperation2Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase3(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("foo"), - }, - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation3Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase4(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveList: []*InputService18TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - NoRecurse: aws.String("bar"), - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation4Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foobar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase5(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveList: []*InputService18TestShapeRecursiveStructType{ - { - NoRecurse: aws.String("foo"), - }, - { - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - NoRecurse: aws.String("bar"), - }, - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation5Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`foobar`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService18ProtocolTestRecursiveShapesCase6(t *testing.T) { - svc := NewInputService18ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService18TestShapeInputShape{ - RecursiveStruct: &InputService18TestShapeRecursiveStructType{ - RecursiveMap: &map[string]*InputService18TestShapeRecursiveStructType{ - "bar": { - NoRecurse: aws.String("bar"), - }, - "foo": { - NoRecurse: aws.String("foo"), - }, - }, - }, - } - req, _ := svc.InputService18TestCaseOperation6Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert body - assert.NotNil(t, r.Body) - body := util.SortXML(r.Body) - assert.Equal(t, util.Trim(`barbarfoofoo`), util.Trim(string(body))) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - -} - -func TestInputService19ProtocolTestTimestampInHeaderCase1(t *testing.T) { - svc := NewInputService19ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService19TestShapeInputShape{ - TimeArgInHeader: aws.Time(time.Unix(1422172800, 0)), - } - req, _ := svc.InputService19TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - restxml.Build(req) - assert.NoError(t, req.Error) - - // assert URL - assert.Equal(t, "https://test/path", r.URL.String()) - - // assert headers - assert.Equal(t, "Sun, 25 Jan 2015 08:00:00 GMT", r.Header.Get("x-amz-timearg")) - -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/restxml.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/restxml.go deleted file mode 100644 index 9a952ee1..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/restxml.go +++ /dev/null @@ -1,48 +0,0 @@ -package restxml - -//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/rest-xml.json build_test.go -//go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/output/rest-xml.json unmarshal_test.go - -import ( - "bytes" - "encoding/xml" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/query" - "github.com/awslabs/aws-sdk-go/internal/protocol/rest" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" -) - -func Build(r *aws.Request) { - rest.Build(r) - - if t := rest.PayloadType(r.Params); t == "structure" || t == "" { - var buf bytes.Buffer - err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) - if err != nil { - r.Error = err - return - } - r.SetBufferBody(buf.Bytes()) - } -} - -func Unmarshal(r *aws.Request) { - if t := rest.PayloadType(r.Data); t == "structure" || t == "" { - defer r.HTTPResponse.Body.Close() - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, "") - if err != nil { - r.Error = err - return - } - } -} - -func UnmarshalMeta(r *aws.Request) { - rest.Unmarshal(r) -} - -func UnmarshalError(r *aws.Request) { - query.UnmarshalError(r) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go deleted file mode 100644 index d1383a12..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go +++ /dev/null @@ -1,1320 +0,0 @@ -package restxml_test - -import ( - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/restxml" - "github.com/awslabs/aws-sdk-go/internal/signer/v4" - - "bytes" - "encoding/json" - "encoding/xml" - "github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil" - "github.com/awslabs/aws-sdk-go/internal/util" - "github.com/stretchr/testify/assert" - "io" - "io/ioutil" - "net/http" - "net/url" - "testing" - "time" -) - -var _ bytes.Buffer // always import bytes -var _ http.Request -var _ json.Marshaler -var _ time.Time -var _ xmlutil.XMLNode -var _ xml.Attr -var _ = ioutil.Discard -var _ = util.Trim("") -var _ = url.Values{} -var _ = io.EOF - -// OutputService1ProtocolTest is a client for OutputService1ProtocolTest. -type OutputService1ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService1ProtocolTest client. -func NewOutputService1ProtocolTest(config *aws.Config) *OutputService1ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice1protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService1ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation1 == nil { - opOutputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService1TestCaseOperation1, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input) (output *OutputService1TestShapeOutputShape, err error) { - req, out := c.OutputService1TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService1TestCaseOperation1 *aws.Operation - -// OutputService1TestCaseOperation2Request generates a request for the OutputService1TestCaseOperation2 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2Request(input *OutputService1TestShapeOutputService1TestCaseOperation2Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation2 == nil { - opOutputService1TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation2Input{} - } - - req = c.newRequest(opOutputService1TestCaseOperation2, input, output) - output = &OutputService1TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2(input *OutputService1TestShapeOutputService1TestCaseOperation2Input) (output *OutputService1TestShapeOutputShape, err error) { - req, out := c.OutputService1TestCaseOperation2Request(input) - output = out - err = req.Send() - return -} - -var opOutputService1TestCaseOperation2 *aws.Operation - -type OutputService1TestShapeOutputService1TestCaseOperation2Input struct { - metadataOutputService1TestShapeOutputService1TestCaseOperation2Input `json:"-", xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation2Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - metadataOutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestShapeOutputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService1TestShapeOutputShape struct { - Char *string `type:"character"` - - Double *float64 `type:"double"` - - FalseBool *bool `type:"boolean"` - - Float *float64 `type:"float"` - - ImaHeader *string `location:"header" type:"string"` - - ImaHeaderLocation *string `location:"header" locationName:"X-Foo" type:"string"` - - Long *int64 `type:"long"` - - Num *int64 `locationName:"FooNum" type:"integer"` - - Str *string `type:"string"` - - Timestamp *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `type:"boolean"` - - metadataOutputService1TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService1TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService2ProtocolTest is a client for OutputService2ProtocolTest. -type OutputService2ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService2ProtocolTest client. -func NewOutputService2ProtocolTest(config *aws.Config) *OutputService2ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice2protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService2ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *aws.Request, output *OutputService2TestShapeOutputShape) { - - if opOutputService2TestCaseOperation1 == nil { - opOutputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService2TestCaseOperation1, input, output) - output = &OutputService2TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (output *OutputService2TestShapeOutputShape, err error) { - req, out := c.OutputService2TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService2TestCaseOperation1 *aws.Operation - -type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { - metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService2TestShapeOutputShape struct { - Blob []byte `type:"blob"` - - metadataOutputService2TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService2TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService3ProtocolTest is a client for OutputService3ProtocolTest. -type OutputService3ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService3ProtocolTest client. -func NewOutputService3ProtocolTest(config *aws.Config) *OutputService3ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice3protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService3ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *aws.Request, output *OutputService3TestShapeOutputShape) { - - if opOutputService3TestCaseOperation1 == nil { - opOutputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService3TestCaseOperation1, input, output) - output = &OutputService3TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (output *OutputService3TestShapeOutputShape, err error) { - req, out := c.OutputService3TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService3TestCaseOperation1 *aws.Operation - -type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { - metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService3TestShapeOutputShape struct { - ListMember []*string `type:"list"` - - metadataOutputService3TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService3TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService4ProtocolTest is a client for OutputService4ProtocolTest. -type OutputService4ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService4ProtocolTest client. -func NewOutputService4ProtocolTest(config *aws.Config) *OutputService4ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice4protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService4ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *aws.Request, output *OutputService4TestShapeOutputShape) { - - if opOutputService4TestCaseOperation1 == nil { - opOutputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService4TestCaseOperation1, input, output) - output = &OutputService4TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (output *OutputService4TestShapeOutputShape, err error) { - req, out := c.OutputService4TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService4TestCaseOperation1 *aws.Operation - -type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { - metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService4TestShapeOutputShape struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService4TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService4TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService5ProtocolTest is a client for OutputService5ProtocolTest. -type OutputService5ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService5ProtocolTest client. -func NewOutputService5ProtocolTest(config *aws.Config) *OutputService5ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice5protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService5ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *aws.Request, output *OutputService5TestShapeOutputShape) { - - if opOutputService5TestCaseOperation1 == nil { - opOutputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService5TestCaseOperation1, input, output) - output = &OutputService5TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (output *OutputService5TestShapeOutputShape, err error) { - req, out := c.OutputService5TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService5TestCaseOperation1 *aws.Operation - -type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { - metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService5TestShapeOutputShape struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService5TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService5TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService6ProtocolTest is a client for OutputService6ProtocolTest. -type OutputService6ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService6ProtocolTest client. -func NewOutputService6ProtocolTest(config *aws.Config) *OutputService6ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice6protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService6ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *aws.Request, output *OutputService6TestShapeOutputShape) { - - if opOutputService6TestCaseOperation1 == nil { - opOutputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService6TestCaseOperation1, input, output) - output = &OutputService6TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (output *OutputService6TestShapeOutputShape, err error) { - req, out := c.OutputService6TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService6TestCaseOperation1 *aws.Operation - -type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { - metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeOutputShape struct { - Map *map[string]*OutputService6TestShapeSingleStructure `type:"map"` - - metadataOutputService6TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService6TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService6TestShapeSingleStructure struct { - Foo *string `locationName:"foo" type:"string"` - - metadataOutputService6TestShapeSingleStructure `json:"-", xml:"-"` -} - -type metadataOutputService6TestShapeSingleStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService7ProtocolTest is a client for OutputService7ProtocolTest. -type OutputService7ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService7ProtocolTest client. -func NewOutputService7ProtocolTest(config *aws.Config) *OutputService7ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice7protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService7ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *aws.Request, output *OutputService7TestShapeOutputShape) { - - if opOutputService7TestCaseOperation1 == nil { - opOutputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService7TestCaseOperation1, input, output) - output = &OutputService7TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (output *OutputService7TestShapeOutputShape, err error) { - req, out := c.OutputService7TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService7TestCaseOperation1 *aws.Operation - -type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { - metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService7TestShapeOutputShape struct { - Map *map[string]*string `type:"map" flattened:"true"` - - metadataOutputService7TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService7TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService8ProtocolTest is a client for OutputService8ProtocolTest. -type OutputService8ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService8ProtocolTest client. -func NewOutputService8ProtocolTest(config *aws.Config) *OutputService8ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice8protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService8ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *aws.Request, output *OutputService8TestShapeOutputShape) { - - if opOutputService8TestCaseOperation1 == nil { - opOutputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService8TestCaseOperation1, input, output) - output = &OutputService8TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (output *OutputService8TestShapeOutputShape, err error) { - req, out := c.OutputService8TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService8TestCaseOperation1 *aws.Operation - -type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { - metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService8TestShapeOutputShape struct { - Map *map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map"` - - metadataOutputService8TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService8TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService9ProtocolTest is a client for OutputService9ProtocolTest. -type OutputService9ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService9ProtocolTest client. -func NewOutputService9ProtocolTest(config *aws.Config) *OutputService9ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice9protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService9ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *aws.Request, output *OutputService9TestShapeOutputShape) { - - if opOutputService9TestCaseOperation1 == nil { - opOutputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService9TestCaseOperation1, input, output) - output = &OutputService9TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (output *OutputService9TestShapeOutputShape, err error) { - req, out := c.OutputService9TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService9TestCaseOperation1 *aws.Operation - -type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { - metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeOutputService9TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService9TestShapeOutputShape struct { - Data *OutputService9TestShapeSingleStructure `type:"structure"` - - Header *string `location:"header" locationName:"X-Foo" type:"string"` - - metadataOutputService9TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Data"` -} - -type OutputService9TestShapeSingleStructure struct { - Foo *string `type:"string"` - - metadataOutputService9TestShapeSingleStructure `json:"-", xml:"-"` -} - -type metadataOutputService9TestShapeSingleStructure struct { - SDKShapeTraits bool `type:"structure"` -} - -// OutputService10ProtocolTest is a client for OutputService10ProtocolTest. -type OutputService10ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService10ProtocolTest client. -func NewOutputService10ProtocolTest(config *aws.Config) *OutputService10ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice10protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService10ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *aws.Request, output *OutputService10TestShapeOutputShape) { - - if opOutputService10TestCaseOperation1 == nil { - opOutputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService10TestCaseOperation1, input, output) - output = &OutputService10TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (output *OutputService10TestShapeOutputShape, err error) { - req, out := c.OutputService10TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService10TestCaseOperation1 *aws.Operation - -type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { - metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService10TestShapeOutputService10TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService10TestShapeOutputShape struct { - Stream []byte `type:"blob"` - - metadataOutputService10TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService10TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure" payload:"Stream"` -} - -// OutputService11ProtocolTest is a client for OutputService11ProtocolTest. -type OutputService11ProtocolTest struct { - *aws.Service -} - -// New returns a new OutputService11ProtocolTest client. -func NewOutputService11ProtocolTest(config *aws.Config) *OutputService11ProtocolTest { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "outputservice11protocoltest", - APIVersion: "", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - return &OutputService11ProtocolTest{service} -} - -// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any -// custom request initialization. -func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - return req -} - -// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *aws.Request, output *OutputService11TestShapeOutputShape) { - - if opOutputService11TestCaseOperation1 == nil { - opOutputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - req = c.newRequest(opOutputService11TestCaseOperation1, input, output) - output = &OutputService11TestShapeOutputShape{} - req.Data = output - return -} - -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (output *OutputService11TestShapeOutputShape, err error) { - req, out := c.OutputService11TestCaseOperation1Request(input) - output = out - err = req.Send() - return -} - -var opOutputService11TestCaseOperation1 *aws.Operation - -type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { - metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-", xml:"-"` -} - -type metadataOutputService11TestShapeOutputService11TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type OutputService11TestShapeOutputShape struct { - Char *string `location:"header" locationName:"x-char" type:"character"` - - Double *float64 `location:"header" locationName:"x-double" type:"double"` - - FalseBool *bool `location:"header" locationName:"x-false-bool" type:"boolean"` - - Float *float64 `location:"header" locationName:"x-float" type:"float"` - - Integer *int64 `location:"header" locationName:"x-int" type:"integer"` - - Long *int64 `location:"header" locationName:"x-long" type:"long"` - - Str *string `location:"header" locationName:"x-str" type:"string"` - - Timestamp *time.Time `location:"header" locationName:"x-timestamp" type:"timestamp" timestampFormat:"iso8601"` - - TrueBool *bool `location:"header" locationName:"x-true-bool" type:"boolean"` - - metadataOutputService11TestShapeOutputShape `json:"-", xml:"-"` -} - -type metadataOutputService11TestShapeOutputShape struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - buf := bytes.NewReader([]byte("myname123falsetrue1.21.3200a2015-01-25T08:00:00Z")) - req, out := svc.OutputService1TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("ImaHeader", "test") - req.HTTPResponse.Header.Set("X-Foo", "abc") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, "test", *out.ImaHeader) - assert.Equal(t, "abc", *out.ImaHeaderLocation) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "myname", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService1ProtocolTestScalarMembersCase2(t *testing.T) { - svc := NewOutputService1ProtocolTest(nil) - - buf := bytes.NewReader([]byte("123falsetrue1.21.3200a2015-01-25T08:00:00Z")) - req, out := svc.OutputService1TestCaseOperation2Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("ImaHeader", "test") - req.HTTPResponse.Header.Set("X-Foo", "abc") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.3, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.2, *out.Float) - assert.Equal(t, "test", *out.ImaHeader) - assert.Equal(t, "abc", *out.ImaHeaderLocation) - assert.Equal(t, int64(200), *out.Long) - assert.Equal(t, int64(123), *out.Num) - assert.Equal(t, "", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} - -func TestOutputService2ProtocolTestBlobCase1(t *testing.T) { - svc := NewOutputService2ProtocolTest(nil) - - buf := bytes.NewReader([]byte("dmFsdWU=")) - req, out := svc.OutputService2TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "value", string(out.Blob)) - -} - -func TestOutputService3ProtocolTestListsCase1(t *testing.T) { - svc := NewOutputService3ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService3TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService4ProtocolTestListWithCustomMemberNameCase1(t *testing.T) { - svc := NewOutputService4ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService4TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService5ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewOutputService5ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc123")) - req, out := svc.OutputService5TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.ListMember[0]) - assert.Equal(t, "123", *out.ListMember[1]) - -} - -func TestOutputService6ProtocolTestNormalMapCase1(t *testing.T) { - svc := NewOutputService6ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService6TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"].Foo) - assert.Equal(t, "bar", *(*out.Map)["qux"].Foo) - -} - -func TestOutputService7ProtocolTestFlattenedMapCase1(t *testing.T) { - svc := NewOutputService7ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService7TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"]) - assert.Equal(t, "bar", *(*out.Map)["qux"]) - -} - -func TestOutputService8ProtocolTestNamedMapCase1(t *testing.T) { - svc := NewOutputService8ProtocolTest(nil) - - buf := bytes.NewReader([]byte("quxbarbazbam")) - req, out := svc.OutputService8TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "bam", *(*out.Map)["baz"]) - assert.Equal(t, "bar", *(*out.Map)["qux"]) - -} - -func TestOutputService9ProtocolTestXMLPayloadCase1(t *testing.T) { - svc := NewOutputService9ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc")) - req, out := svc.OutputService9TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("X-Foo", "baz") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", *out.Data.Foo) - assert.Equal(t, "baz", *out.Header) - -} - -func TestOutputService10ProtocolTestStreamingPayloadCase1(t *testing.T) { - svc := NewOutputService10ProtocolTest(nil) - - buf := bytes.NewReader([]byte("abc")) - req, out := svc.OutputService10TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "abc", string(out.Stream)) - -} - -func TestOutputService11ProtocolTestScalarMembersInHeadersCase1(t *testing.T) { - svc := NewOutputService11ProtocolTest(nil) - - buf := bytes.NewReader([]byte("")) - req, out := svc.OutputService11TestCaseOperation1Request(nil) - req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}} - - // set headers - req.HTTPResponse.Header.Set("x-char", "a") - req.HTTPResponse.Header.Set("x-double", "1.5") - req.HTTPResponse.Header.Set("x-false-bool", "false") - req.HTTPResponse.Header.Set("x-float", "1.5") - req.HTTPResponse.Header.Set("x-int", "1") - req.HTTPResponse.Header.Set("x-long", "100") - req.HTTPResponse.Header.Set("x-str", "string") - req.HTTPResponse.Header.Set("x-timestamp", "Sun, 25 Jan 2015 08:00:00 GMT") - req.HTTPResponse.Header.Set("x-true-bool", "true") - - // unmarshal response - restxml.UnmarshalMeta(req) - restxml.Unmarshal(req) - assert.NoError(t, req.Error) - - // assert response - assert.NotNil(t, out) // ensure out variable is used - assert.Equal(t, "a", *out.Char) - assert.Equal(t, 1.5, *out.Double) - assert.Equal(t, false, *out.FalseBool) - assert.Equal(t, 1.5, *out.Float) - assert.Equal(t, int64(1), *out.Integer) - assert.Equal(t, int64(100), *out.Long) - assert.Equal(t, "string", *out.Str) - assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String()) - assert.Equal(t, true, *out.TrueBool) - -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/build.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/build.go deleted file mode 100644 index cfe05acb..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/build.go +++ /dev/null @@ -1,263 +0,0 @@ -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -func BuildXML(params interface{}, e *xml.Encoder) error { - b := xmlBuilder{encoder: e, namespaces: map[string]string{}} - root := NewXMLElement(xml.Name{}) - if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { - return err - } - for _, c := range root.Children { - for _, v := range c { - return StructToXML(e, v, false) - } - } - return nil -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type xmlBuilder struct { - encoder *xml.Encoder - namespaces map[string]string -} - -func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - value = elemOf(value) - if !value.IsValid() { // no need to handle zero values - return nil - } else if tag.Get("location") != "" { // don't handle non-body location values - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := value.Type().FieldByName("SDKShapeTraits"); ok { - tag = tag + reflect.StructTag(" ") + field.Tag - } - return b.buildStruct(value, current, tag) - case "list": - return b.buildList(value, current, tag) - case "map": - return b.buildMap(value, current, tag) - default: - return b.buildScalar(value, current, tag) - } -} - -func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - fieldAdded := false - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - child := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - - // there is an xmlNamespace associated with this struct - if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" { - ns := xml.Attr{ - Name: xml.Name{Local: "xmlns"}, - Value: uri, - } - if prefix != "" { - b.namespaces[prefix] = uri // register the namespace - ns.Name.Local = "xmlns:" + prefix - } - - child.Attr = append(child.Attr, ns) - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - member := elemOf(value.Field(i)) - field := t.Field(i) - mTag := field.Tag - - if mTag.Get("location") != "" { // skip non-body members - continue - } - - memberName := mTag.Get("locationName") - if memberName == "" { - memberName = field.Name - mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`) - } - if err := b.buildValue(member, child, mTag); err != nil { - return err - } - - fieldAdded = true - } - - if fieldAdded { // only append this child if we have one ore more valid members - current.AddChild(child) - } - - return nil -} - -func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted lists - return nil - } - - // check for unflattened list member - flattened := tag.Get("flattened") != "" - - xname := xml.Name{Local: tag.Get("locationName")} - if flattened { - for i := 0; i < value.Len(); i++ { - child := NewXMLElement(xname) - current.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } else { - list := NewXMLElement(xname) - current.AddChild(list) - - for i := 0; i < value.Len(); i++ { - iname := tag.Get("locationNameList") - if iname == "" { - iname = "member" - } - - child := NewXMLElement(xml.Name{Local: iname}) - list.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } - - return nil -} - -func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted maps - return nil - } - - maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - current.AddChild(maproot) - current = maproot - - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - // sorting is not required for compliance, but it makes testing easier - keys := make([]string, value.Len()) - for i, k := range value.MapKeys() { - keys[i] = k.String() - } - sort.Strings(keys) - - for _, k := range keys { - v := value.MapIndex(reflect.ValueOf(k)) - - mapcur := current - if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps - child := NewXMLElement(xml.Name{Local: "entry"}) - mapcur.AddChild(child) - mapcur = child - } - - kchild := NewXMLElement(xml.Name{Local: kname}) - kchild.Text = k - vchild := NewXMLElement(xml.Name{Local: vname}) - mapcur.AddChild(kchild) - mapcur.AddChild(vchild) - - if err := b.buildValue(v, vchild, ""); err != nil { - return err - } - } - - return nil -} - -func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - var str string - switch converted := value.Interface().(type) { - case string: - str = converted - case []byte: - if !value.IsNil() { - str = base64.StdEncoding.EncodeToString(converted) - } - case bool: - str = strconv.FormatBool(converted) - case int64: - str = strconv.FormatInt(converted, 10) - case int: - str = strconv.Itoa(converted) - case float64: - str = strconv.FormatFloat(converted, 'f', -1, 64) - case float32: - str = strconv.FormatFloat(float64(converted), 'f', -1, 32) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - str = converted.UTC().Format(ISO8601UTC) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", - tag.Get("locationName"), value.Interface(), value.Type().Name()) - } - - xname := xml.Name{Local: tag.Get("locationName")} - if tag.Get("xmlAttribute") != "" { // put into current node's attribute list - attr := xml.Attr{Name: xname, Value: str} - current.Attr = append(current.Attr, attr) - } else { // regular text node - current.AddChild(&XMLNode{Name: xname, Text: str}) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go deleted file mode 100644 index 89c64f2c..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go +++ /dev/null @@ -1,251 +0,0 @@ -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "io" - "reflect" - "strconv" - "strings" - "time" -) - -func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, _ := XMLToStruct(d, nil) - if n.Children != nil { - for _, root := range n.Children { - for _, c := range root { - if wrappedChild, ok := c.Children[wrapper]; ok { - c = wrappedChild[0] // pull out wrapped element - } - - err := parse(reflect.ValueOf(v), c, "") - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } - } - return nil - } - return nil -} - -func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - rtype := r.Type() - if rtype.Kind() == reflect.Ptr { - rtype = rtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch rtype.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := rtype.FieldByName("SDKShapeTraits"); ok { - tag = field.Tag - } - return parseStruct(r, node, tag) - case "list": - return parseList(r, node, tag) - case "map": - return parseMap(r, node, tag) - default: - return parseScalar(r, node, tag) - } -} - -func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - if r.IsNil() { // create the structure if it's nil - s := reflect.New(r.Type().Elem()) - r.Set(s) - r = s - } - - r = r.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return parseStruct(r.FieldByName(payload), node, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if c := field.Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - // try to find the field by name in elements - elems := node.Children[name] - - if elems == nil { // try to find the field in attributes - for _, a := range node.Attr { - if name == a.Name.Local { - // turn this into a text node for de-serializing - elems = []*XMLNode{{Text: a.Value}} - } - } - } - - member := r.FieldByName(field.Name) - for _, elem := range elems { - err := parse(member, elem, field.Tag) - if err != nil { - return err - } - } - } - return nil -} - -func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - - if tag.Get("flattened") == "" { // look at all item entries - mname := "member" - if name := tag.Get("locationNameList"); name != "" { - mname = name - } - - if Children, ok := node.Children[mname]; ok { - if r.IsNil() { - r.Set(reflect.MakeSlice(t, len(Children), len(Children))) - } - - for i, c := range Children { - err := parse(r.Index(i), c, "") - if err != nil { - return err - } - } - } - } else { // flattened list means this is a single element - if r.IsNil() { - r.Set(reflect.MakeSlice(t, 0, 0)) - } - - childR := reflect.Zero(t.Elem()) - r.Set(reflect.Append(r, childR)) - err := parse(r.Index(r.Len()-1), node, "") - if err != nil { - return err - } - } - - return nil -} - -func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - t = t.Elem() - if r.IsNil() { - r.Set(reflect.New(t)) - r.Elem().Set(reflect.MakeMap(t)) - } - - r = r.Elem() - } - - if tag.Get("flattened") == "" { // look at all child entries - for _, entry := range node.Children["entry"] { - parseMapEntry(r, entry, tag) - } - } else { // this element is itself an entry - parseMapEntry(r, node, tag) - } - - return nil -} - -func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - keys, ok := node.Children[kname] - values := node.Children[vname] - if ok { - for i, key := range keys { - keyR := reflect.ValueOf(key.Text) - value := values[i] - valueR := reflect.New(r.Type().Elem()).Elem() - - parse(valueR, value, "") - r.SetMapIndex(keyR, valueR) - } - } - return nil -} - -func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - switch r.Interface().(type) { - case *string: - r.Set(reflect.ValueOf(&node.Text)) - return nil - case []byte: - b, err := base64.StdEncoding.DecodeString(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(b)) - case *bool: - v, err := strconv.ParseBool(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *int64: - v, err := strconv.ParseInt(node.Text, 10, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *float64: - v, err := strconv.ParseFloat(node.Text, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - t, err := time.Parse(ISO8601UTC, node.Text) - if err != nil { - return err - } else { - r.Set(reflect.ValueOf(&t)) - } - default: - return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type()) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/xml_to_struct.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/xml_to_struct.go deleted file mode 100644 index 6e92da3e..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/protocol/xml/xmlutil/xml_to_struct.go +++ /dev/null @@ -1,100 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "io" - "sort" -) - -type XMLNode struct { - Name xml.Name `json:",omitempty"` - Children map[string][]*XMLNode `json:",omitempty"` - Text string `json:",omitempty"` - Attr []xml.Attr `json:",omitempty"` -} - -func NewXMLElement(name xml.Name) *XMLNode { - return &XMLNode{ - Name: name, - Children: map[string][]*XMLNode{}, - Attr: []xml.Attr{}, - } -} - -func (n *XMLNode) AddChild(child *XMLNode) { - if _, ok := n.Children[child.Name.Local]; !ok { - n.Children[child.Name.Local] = []*XMLNode{} - } - n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child) -} - -func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { - out := &XMLNode{} - for { - tok, err := d.Token() - if tok == nil || err == io.EOF { - break - } - if err != nil { - return out, err - } - - switch typed := tok.(type) { - case xml.CharData: - out.Text = string(typed.Copy()) - case xml.StartElement: - el := typed.Copy() - out.Attr = el.Attr - if out.Children == nil { - out.Children = map[string][]*XMLNode{} - } - - name := typed.Name.Local - slice := out.Children[name] - if slice == nil { - slice = []*XMLNode{} - } - node, e := XMLToStruct(d, &el) - if e != nil { - return out, e - } - node.Name = typed.Name - slice = append(slice, node) - out.Children[name] = slice - case xml.EndElement: - if s != nil && s.Name.Local == typed.Name.Local { // matching end token - return out, nil - } - } - } - return out, nil -} - -func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error { - e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr}) - - if node.Text != "" { - e.EncodeToken(xml.CharData([]byte(node.Text))) - } else if sorted { - sortedNames := []string{} - for k := range node.Children { - sortedNames = append(sortedNames, k) - } - sort.Strings(sortedNames) - - for _, k := range sortedNames { - for _, v := range node.Children[k] { - StructToXML(e, v, sorted) - } - } - } else { - for _, c := range node.Children { - for _, v := range c { - StructToXML(e, v, sorted) - } - } - } - - e.EncodeToken(xml.EndElement{Name: node.Name}) - return e.Flush() -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4.go deleted file mode 100644 index 89e677e1..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4.go +++ /dev/null @@ -1,301 +0,0 @@ -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/awslabs/aws-sdk-go/aws" -) - -const ( - authHeaderPrefix = "AWS4-HMAC-SHA256" - timeFormat = "20060102T150405Z" - shortTimeFormat = "20060102" -) - -var ignoredHeaders = map[string]bool{ - "Authorization": true, - "Content-Type": true, - "Content-Length": true, - "User-Agent": true, -} - -type signer struct { - Request *http.Request - Time time.Time - ExpireTime time.Duration - ServiceName string - Region string - AccessKeyID string - SecretAccessKey string - SessionToken string - Query url.Values - Body io.ReadSeeker - Debug uint - Logger io.Writer - - isPresign bool - formattedTime string - formattedShortTime string - - signedHeaders string - canonicalHeaders string - canonicalString string - credentialString string - stringToSign string - signature string - authorization string -} - -// Sign requests with signature version 4. -func Sign(req *aws.Request) { - creds, err := req.Service.Config.Credentials.Credentials() - if err != nil { - req.Error = err - return - } - - region := req.Service.SigningRegion - if region == "" { - region = req.Service.Config.Region - } - - s := signer{ - Request: req.HTTPRequest, - Time: req.Time, - ExpireTime: req.ExpireTime, - Query: req.HTTPRequest.URL.Query(), - Body: req.Body, - ServiceName: req.Service.ServiceName, - Region: region, - AccessKeyID: creds.AccessKeyID, - SecretAccessKey: creds.SecretAccessKey, - SessionToken: creds.SessionToken, - Debug: req.Service.Config.LogLevel, - Logger: req.Service.Config.Logger, - } - s.sign() - return -} - -func (v4 *signer) sign() { - if v4.ExpireTime != 0 { - v4.isPresign = true - } - - if v4.isPresign { - v4.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if v4.SessionToken != "" { - v4.Query.Set("X-Amz-Security-Token", v4.SessionToken) - } else { - v4.Query.Del("X-Amz-Security-Token") - } - } else if v4.SessionToken != "" { - v4.Request.Header.Set("X-Amz-Security-Token", v4.SessionToken) - } - - v4.build() - - if v4.Debug > 0 { - 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) - fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n") - fmt.Fprintln(out, v4.Request.URL) - fmt.Fprintf(out, "-----------------------------------------------------\n") - } -} - -func (v4 *signer) build() { - v4.buildTime() // no depends - v4.buildCredentialString() // no depends - if v4.isPresign { - v4.buildQuery() // no depends - } - v4.buildCanonicalHeaders() // depends on cred string - v4.buildCanonicalString() // depends on canon headers / signed headers - v4.buildStringToSign() // depends on canon string - v4.buildSignature() // depends on string to sign - - if v4.isPresign { - v4.Request.URL.RawQuery += "&X-Amz-Signature=" + v4.signature - } else { - parts := []string{ - authHeaderPrefix + " Credential=" + v4.AccessKeyID + "/" + v4.credentialString, - "SignedHeaders=" + v4.signedHeaders, - "Signature=" + v4.signature, - } - v4.Request.Header.Set("Authorization", strings.Join(parts, ", ")) - } -} - -func (v4 *signer) buildTime() { - v4.formattedTime = v4.Time.UTC().Format(timeFormat) - v4.formattedShortTime = v4.Time.UTC().Format(shortTimeFormat) - - if v4.isPresign { - duration := int64(v4.ExpireTime / time.Second) - v4.Query.Set("X-Amz-Date", v4.formattedTime) - v4.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) - } else { - v4.Request.Header.Set("X-Amz-Date", v4.formattedTime) - } -} - -func (v4 *signer) buildCredentialString() { - v4.credentialString = strings.Join([]string{ - v4.formattedShortTime, - v4.Region, - v4.ServiceName, - "aws4_request", - }, "/") - - if v4.isPresign { - v4.Query.Set("X-Amz-Credential", v4.AccessKeyID+"/"+v4.credentialString) - } -} - -func (v4 *signer) buildQuery() { - for k, h := range v4.Request.Header { - if strings.HasPrefix(http.CanonicalHeaderKey(k), "X-Amz-") { - continue // never hoist x-amz-* headers, they must be signed - } - if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { - continue // never hoist ignored headers - } - - v4.Request.Header.Del(k) - v4.Query.Del(k) - for _, v := range h { - v4.Query.Add(k, v) - } - } -} - -func (v4 *signer) buildCanonicalHeaders() { - headers := make([]string, 0) - headers = append(headers, "host") - for k := range v4.Request.Header { - if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok { - continue // ignored header - } - headers = append(headers, strings.ToLower(k)) - } - sort.Strings(headers) - - v4.signedHeaders = strings.Join(headers, ";") - - if v4.isPresign { - v4.Query.Set("X-Amz-SignedHeaders", v4.signedHeaders) - } - - 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.canonicalHeaders = strings.Join(headerValues, "\n") -} - -func (v4 *signer) buildCanonicalString() { - v4.Request.URL.RawQuery = v4.Query.Encode() - uri := v4.Request.URL.Opaque - if uri != "" { - uri = "/" + strings.Join(strings.Split(uri, "/")[3:], "/") - } else { - uri = v4.Request.URL.Path - } - if uri == "" { - uri = "/" - } - - v4.canonicalString = strings.Join([]string{ - v4.Request.Method, - uri, - v4.Request.URL.RawQuery, - v4.canonicalHeaders + "\n", - v4.signedHeaders, - v4.bodyDigest(), - }, "\n") -} - -func (v4 *signer) buildStringToSign() { - v4.stringToSign = strings.Join([]string{ - authHeaderPrefix, - v4.formattedTime, - v4.credentialString, - hex.EncodeToString(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 = hex.EncodeToString(signature) -} - -func (v4 *signer) bodyDigest() string { - hash := v4.Request.Header.Get("X-Amz-Content-Sha256") - if hash == "" { - if v4.isPresign && v4.ServiceName == "s3" { - hash = "UNSIGNED-PAYLOAD" - } else if v4.Body == nil { - hash = hex.EncodeToString(makeSha256([]byte{})) - } else { - hash = hex.EncodeToString(makeSha256Reader(v4.Body)) - } - 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.ReadSeeker) []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) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4_test.go deleted file mode 100644 index fb15c394..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/internal/signer/v4/v4_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func buildSigner(serviceName string, region string, signTime time.Time, expireTime time.Duration, body string) signer { - endpoint := "https://" + serviceName + "." + region + ".amazonaws.com" - reader := strings.NewReader(body) - req, _ := http.NewRequest("POST", endpoint, reader) - req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()" - 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))) - req.Header.Add("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* ()") - - return signer{ - Request: req, - Time: signTime, - ExpireTime: expireTime, - Query: req.URL.Query(), - 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 TestPresignRequest(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 300*time.Second, "{}") - signer.sign() - - expectedDate := "19700101T000000Z" - expectedHeaders := "host;x-amz-meta-other-header;x-amz-target" - expectedSig := "41c18d68f9191079dfeead4e3f034328f89d86c79f8e9d51dd48bb70eaf623fc" - expectedCred := "AKID/19700101/us-east-1/dynamodb/aws4_request" - - q := signer.Request.URL.Query() - assert.Equal(t, expectedSig, q.Get("X-Amz-Signature")) - assert.Equal(t, expectedCred, q.Get("X-Amz-Credential")) - assert.Equal(t, expectedHeaders, q.Get("X-Amz-SignedHeaders")) - assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) -} - -func TestSignRequest(t *testing.T) { - signer := buildSigner("dynamodb", "us-east-1", time.Unix(0, 0), 0, "{}") - signer.sign() - - expectedDate := "19700101T000000Z" - expectedSig := "AWS4-HMAC-SHA256 Credential=AKID/19700101/us-east-1/dynamodb/aws4_request, SignedHeaders=host;x-amz-date;x-amz-meta-other-header;x-amz-security-token;x-amz-target, Signature=0196959cabd964bd10c05217b40ed151882dd394190438bab0c658dafdbff7a1" - - q := signer.Request.Header - assert.Equal(t, expectedSig, q.Get("Authorization")) - assert.Equal(t, expectedDate, q.Get("X-Amz-Date")) -} - -func BenchmarkPresignRequest(b *testing.B) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}") - for i := 0; i < b.N; i++ { - signer.sign() - } -} - -func BenchmarkSignRequest(b *testing.B) { - signer := buildSigner("dynamodb", "us-east-1", time.Now(), 0, "{}") - for i := 0; i < b.N; i++ { - signer.sign() - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/api.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/api.go deleted file mode 100644 index 5fd28d4e..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/api.go +++ /dev/null @@ -1,4917 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -// Package s3 provides a client for Amazon Simple Storage Service. -package s3 - -import ( - "io" - "sync" - "time" - - "github.com/awslabs/aws-sdk-go/aws" -) - -var oprw sync.Mutex - -// AbortMultipartUploadRequest generates a request for the AbortMultipartUpload operation. -func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *aws.Request, output *AbortMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opAbortMultipartUpload == nil { - opAbortMultipartUpload = &aws.Operation{ - Name: "AbortMultipartUpload", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &AbortMultipartUploadInput{} - } - - req = c.newRequest(opAbortMultipartUpload, input, output) - output = &AbortMultipartUploadOutput{} - req.Data = output - return -} - -// Aborts a multipart upload. -// -// To verify that all parts have been removed, so you don't get charged for -// the part storage, you should call the List Parts operation and ensure the -// parts list is empty. -func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (output *AbortMultipartUploadOutput, err error) { - req, out := c.AbortMultipartUploadRequest(input) - output = out - err = req.Send() - return -} - -var opAbortMultipartUpload *aws.Operation - -// CompleteMultipartUploadRequest generates a request for the CompleteMultipartUpload operation. -func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *aws.Request, output *CompleteMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCompleteMultipartUpload == nil { - opCompleteMultipartUpload = &aws.Operation{ - Name: "CompleteMultipartUpload", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &CompleteMultipartUploadInput{} - } - - req = c.newRequest(opCompleteMultipartUpload, input, output) - output = &CompleteMultipartUploadOutput{} - req.Data = output - return -} - -// Completes a multipart upload by assembling previously uploaded parts. -func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (output *CompleteMultipartUploadOutput, err error) { - req, out := c.CompleteMultipartUploadRequest(input) - output = out - err = req.Send() - return -} - -var opCompleteMultipartUpload *aws.Operation - -// CopyObjectRequest generates a request for the CopyObject operation. -func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *aws.Request, output *CopyObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCopyObject == nil { - opCopyObject = &aws.Operation{ - Name: "CopyObject", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &CopyObjectInput{} - } - - req = c.newRequest(opCopyObject, input, output) - output = &CopyObjectOutput{} - req.Data = output - return -} - -// Creates a copy of an object that is already stored in Amazon S3. -func (c *S3) CopyObject(input *CopyObjectInput) (output *CopyObjectOutput, err error) { - req, out := c.CopyObjectRequest(input) - output = out - err = req.Send() - return -} - -var opCopyObject *aws.Operation - -// CreateBucketRequest generates a request for the CreateBucket operation. -func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *aws.Request, output *CreateBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCreateBucket == nil { - opCreateBucket = &aws.Operation{ - Name: "CreateBucket", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}", - } - } - - if input == nil { - input = &CreateBucketInput{} - } - - req = c.newRequest(opCreateBucket, input, output) - output = &CreateBucketOutput{} - req.Data = output - return -} - -// Creates a new bucket. -func (c *S3) CreateBucket(input *CreateBucketInput) (output *CreateBucketOutput, err error) { - req, out := c.CreateBucketRequest(input) - output = out - err = req.Send() - return -} - -var opCreateBucket *aws.Operation - -// CreateMultipartUploadRequest generates a request for the CreateMultipartUpload operation. -func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *aws.Request, output *CreateMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCreateMultipartUpload == nil { - opCreateMultipartUpload = &aws.Operation{ - Name: "CreateMultipartUpload", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?uploads", - } - } - - if input == nil { - input = &CreateMultipartUploadInput{} - } - - req = c.newRequest(opCreateMultipartUpload, input, output) - output = &CreateMultipartUploadOutput{} - req.Data = output - return -} - -// Initiates a multipart upload and returns an upload ID. -// -// Note: After you initiate multipart upload and upload one or more parts, -// you must either complete or abort multipart upload in order to stop getting -// charged for storage of the uploaded parts. Only after you either complete -// or abort multipart upload, Amazon S3 frees up the parts storage and stops -// charging you for the parts storage. -func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (output *CreateMultipartUploadOutput, err error) { - req, out := c.CreateMultipartUploadRequest(input) - output = out - err = req.Send() - return -} - -var opCreateMultipartUpload *aws.Operation - -// DeleteBucketRequest generates a request for the DeleteBucket operation. -func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *aws.Request, output *DeleteBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucket == nil { - opDeleteBucket = &aws.Operation{ - Name: "DeleteBucket", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}", - } - } - - if input == nil { - input = &DeleteBucketInput{} - } - - req = c.newRequest(opDeleteBucket, input, output) - output = &DeleteBucketOutput{} - req.Data = output - return -} - -// Deletes the bucket. All objects (including all object versions and Delete -// Markers) in the bucket must be deleted before the bucket itself can be deleted. -func (c *S3) DeleteBucket(input *DeleteBucketInput) (output *DeleteBucketOutput, err error) { - req, out := c.DeleteBucketRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucket *aws.Operation - -// DeleteBucketCORSRequest generates a request for the DeleteBucketCORS operation. -func (c *S3) DeleteBucketCORSRequest(input *DeleteBucketCORSInput) (req *aws.Request, output *DeleteBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketCORS == nil { - opDeleteBucketCORS = &aws.Operation{ - Name: "DeleteBucketCors", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?cors", - } - } - - if input == nil { - input = &DeleteBucketCORSInput{} - } - - req = c.newRequest(opDeleteBucketCORS, input, output) - output = &DeleteBucketCORSOutput{} - req.Data = output - return -} - -// Deletes the cors configuration information set for the bucket. -func (c *S3) DeleteBucketCORS(input *DeleteBucketCORSInput) (output *DeleteBucketCORSOutput, err error) { - req, out := c.DeleteBucketCORSRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketCORS *aws.Operation - -// DeleteBucketLifecycleRequest generates a request for the DeleteBucketLifecycle operation. -func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *aws.Request, output *DeleteBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketLifecycle == nil { - opDeleteBucketLifecycle = &aws.Operation{ - Name: "DeleteBucketLifecycle", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?lifecycle", - } - } - - if input == nil { - input = &DeleteBucketLifecycleInput{} - } - - req = c.newRequest(opDeleteBucketLifecycle, input, output) - output = &DeleteBucketLifecycleOutput{} - req.Data = output - return -} - -// Deletes the lifecycle configuration from the bucket. -func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (output *DeleteBucketLifecycleOutput, err error) { - req, out := c.DeleteBucketLifecycleRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketLifecycle *aws.Operation - -// DeleteBucketPolicyRequest generates a request for the DeleteBucketPolicy operation. -func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *aws.Request, output *DeleteBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketPolicy == nil { - opDeleteBucketPolicy = &aws.Operation{ - Name: "DeleteBucketPolicy", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?policy", - } - } - - if input == nil { - input = &DeleteBucketPolicyInput{} - } - - req = c.newRequest(opDeleteBucketPolicy, input, output) - output = &DeleteBucketPolicyOutput{} - req.Data = output - return -} - -// Deletes the policy from the bucket. -func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (output *DeleteBucketPolicyOutput, err error) { - req, out := c.DeleteBucketPolicyRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketPolicy *aws.Operation - -// DeleteBucketReplicationRequest generates a request for the DeleteBucketReplication operation. -func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *aws.Request, output *DeleteBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketReplication == nil { - opDeleteBucketReplication = &aws.Operation{ - Name: "DeleteBucketReplication", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?replication", - } - } - - if input == nil { - input = &DeleteBucketReplicationInput{} - } - - req = c.newRequest(opDeleteBucketReplication, input, output) - output = &DeleteBucketReplicationOutput{} - req.Data = output - return -} - -func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (output *DeleteBucketReplicationOutput, err error) { - req, out := c.DeleteBucketReplicationRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketReplication *aws.Operation - -// DeleteBucketTaggingRequest generates a request for the DeleteBucketTagging operation. -func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *aws.Request, output *DeleteBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketTagging == nil { - opDeleteBucketTagging = &aws.Operation{ - Name: "DeleteBucketTagging", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?tagging", - } - } - - if input == nil { - input = &DeleteBucketTaggingInput{} - } - - req = c.newRequest(opDeleteBucketTagging, input, output) - output = &DeleteBucketTaggingOutput{} - req.Data = output - return -} - -// Deletes the tags from the bucket. -func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (output *DeleteBucketTaggingOutput, err error) { - req, out := c.DeleteBucketTaggingRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketTagging *aws.Operation - -// DeleteBucketWebsiteRequest generates a request for the DeleteBucketWebsite operation. -func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *aws.Request, output *DeleteBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketWebsite == nil { - opDeleteBucketWebsite = &aws.Operation{ - Name: "DeleteBucketWebsite", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?website", - } - } - - if input == nil { - input = &DeleteBucketWebsiteInput{} - } - - req = c.newRequest(opDeleteBucketWebsite, input, output) - output = &DeleteBucketWebsiteOutput{} - req.Data = output - return -} - -// This operation removes the website configuration from the bucket. -func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (output *DeleteBucketWebsiteOutput, err error) { - req, out := c.DeleteBucketWebsiteRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteBucketWebsite *aws.Operation - -// DeleteObjectRequest generates a request for the DeleteObject operation. -func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *aws.Request, output *DeleteObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteObject == nil { - opDeleteObject = &aws.Operation{ - Name: "DeleteObject", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &DeleteObjectInput{} - } - - req = c.newRequest(opDeleteObject, input, output) - output = &DeleteObjectOutput{} - req.Data = output - return -} - -// Removes the null version (if there is one) of an object and inserts a delete -// marker, which becomes the latest version of the object. If there isn't a -// null version, Amazon S3 does not remove any objects. -func (c *S3) DeleteObject(input *DeleteObjectInput) (output *DeleteObjectOutput, err error) { - req, out := c.DeleteObjectRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteObject *aws.Operation - -// DeleteObjectsRequest generates a request for the DeleteObjects operation. -func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *aws.Request, output *DeleteObjectsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteObjects == nil { - opDeleteObjects = &aws.Operation{ - Name: "DeleteObjects", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}?delete", - } - } - - if input == nil { - input = &DeleteObjectsInput{} - } - - req = c.newRequest(opDeleteObjects, input, output) - output = &DeleteObjectsOutput{} - req.Data = output - return -} - -// This operation enables you to delete multiple objects from a bucket using -// a single HTTP request. You may specify up to 1000 keys. -func (c *S3) DeleteObjects(input *DeleteObjectsInput) (output *DeleteObjectsOutput, err error) { - req, out := c.DeleteObjectsRequest(input) - output = out - err = req.Send() - return -} - -var opDeleteObjects *aws.Operation - -// GetBucketACLRequest generates a request for the GetBucketACL operation. -func (c *S3) GetBucketACLRequest(input *GetBucketACLInput) (req *aws.Request, output *GetBucketACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketACL == nil { - opGetBucketACL = &aws.Operation{ - Name: "GetBucketAcl", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?acl", - } - } - - if input == nil { - input = &GetBucketACLInput{} - } - - req = c.newRequest(opGetBucketACL, input, output) - output = &GetBucketACLOutput{} - req.Data = output - return -} - -// Gets the access control policy for the bucket. -func (c *S3) GetBucketACL(input *GetBucketACLInput) (output *GetBucketACLOutput, err error) { - req, out := c.GetBucketACLRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketACL *aws.Operation - -// GetBucketCORSRequest generates a request for the GetBucketCORS operation. -func (c *S3) GetBucketCORSRequest(input *GetBucketCORSInput) (req *aws.Request, output *GetBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketCORS == nil { - opGetBucketCORS = &aws.Operation{ - Name: "GetBucketCors", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?cors", - } - } - - if input == nil { - input = &GetBucketCORSInput{} - } - - req = c.newRequest(opGetBucketCORS, input, output) - output = &GetBucketCORSOutput{} - req.Data = output - return -} - -// Returns the cors configuration for the bucket. -func (c *S3) GetBucketCORS(input *GetBucketCORSInput) (output *GetBucketCORSOutput, err error) { - req, out := c.GetBucketCORSRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketCORS *aws.Operation - -// GetBucketLifecycleRequest generates a request for the GetBucketLifecycle operation. -func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *aws.Request, output *GetBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLifecycle == nil { - opGetBucketLifecycle = &aws.Operation{ - Name: "GetBucketLifecycle", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?lifecycle", - } - } - - if input == nil { - input = &GetBucketLifecycleInput{} - } - - req = c.newRequest(opGetBucketLifecycle, input, output) - output = &GetBucketLifecycleOutput{} - req.Data = output - return -} - -// Returns the lifecycle configuration information set on the bucket. -func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (output *GetBucketLifecycleOutput, err error) { - req, out := c.GetBucketLifecycleRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketLifecycle *aws.Operation - -// GetBucketLocationRequest generates a request for the GetBucketLocation operation. -func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *aws.Request, output *GetBucketLocationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLocation == nil { - opGetBucketLocation = &aws.Operation{ - Name: "GetBucketLocation", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?location", - } - } - - if input == nil { - input = &GetBucketLocationInput{} - } - - req = c.newRequest(opGetBucketLocation, input, output) - output = &GetBucketLocationOutput{} - req.Data = output - return -} - -// Returns the region the bucket resides in. -func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (output *GetBucketLocationOutput, err error) { - req, out := c.GetBucketLocationRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketLocation *aws.Operation - -// GetBucketLoggingRequest generates a request for the GetBucketLogging operation. -func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *aws.Request, output *GetBucketLoggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLogging == nil { - opGetBucketLogging = &aws.Operation{ - Name: "GetBucketLogging", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?logging", - } - } - - if input == nil { - input = &GetBucketLoggingInput{} - } - - req = c.newRequest(opGetBucketLogging, input, output) - output = &GetBucketLoggingOutput{} - req.Data = output - return -} - -// Returns the logging status of a bucket and the permissions users have to -// view and modify that status. To use GET, you must be the bucket owner. -func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (output *GetBucketLoggingOutput, err error) { - req, out := c.GetBucketLoggingRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketLogging *aws.Operation - -// GetBucketNotificationRequest generates a request for the GetBucketNotification operation. -func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationInput) (req *aws.Request, output *GetBucketNotificationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketNotification == nil { - opGetBucketNotification = &aws.Operation{ - Name: "GetBucketNotification", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?notification", - } - } - - if input == nil { - input = &GetBucketNotificationInput{} - } - - req = c.newRequest(opGetBucketNotification, input, output) - output = &GetBucketNotificationOutput{} - req.Data = output - return -} - -// Return the notification configuration of a bucket. -func (c *S3) GetBucketNotification(input *GetBucketNotificationInput) (output *GetBucketNotificationOutput, err error) { - req, out := c.GetBucketNotificationRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketNotification *aws.Operation - -// GetBucketPolicyRequest generates a request for the GetBucketPolicy operation. -func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *aws.Request, output *GetBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketPolicy == nil { - opGetBucketPolicy = &aws.Operation{ - Name: "GetBucketPolicy", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?policy", - } - } - - if input == nil { - input = &GetBucketPolicyInput{} - } - - req = c.newRequest(opGetBucketPolicy, input, output) - output = &GetBucketPolicyOutput{} - req.Data = output - return -} - -// Returns the policy of a specified bucket. -func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (output *GetBucketPolicyOutput, err error) { - req, out := c.GetBucketPolicyRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketPolicy *aws.Operation - -// GetBucketReplicationRequest generates a request for the GetBucketReplication operation. -func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *aws.Request, output *GetBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketReplication == nil { - opGetBucketReplication = &aws.Operation{ - Name: "GetBucketReplication", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?replication", - } - } - - if input == nil { - input = &GetBucketReplicationInput{} - } - - req = c.newRequest(opGetBucketReplication, input, output) - output = &GetBucketReplicationOutput{} - req.Data = output - return -} - -func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (output *GetBucketReplicationOutput, err error) { - req, out := c.GetBucketReplicationRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketReplication *aws.Operation - -// GetBucketRequestPaymentRequest generates a request for the GetBucketRequestPayment operation. -func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *aws.Request, output *GetBucketRequestPaymentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketRequestPayment == nil { - opGetBucketRequestPayment = &aws.Operation{ - Name: "GetBucketRequestPayment", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?requestPayment", - } - } - - if input == nil { - input = &GetBucketRequestPaymentInput{} - } - - req = c.newRequest(opGetBucketRequestPayment, input, output) - output = &GetBucketRequestPaymentOutput{} - req.Data = output - return -} - -// Returns the request payment configuration of a bucket. -func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (output *GetBucketRequestPaymentOutput, err error) { - req, out := c.GetBucketRequestPaymentRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketRequestPayment *aws.Operation - -// GetBucketTaggingRequest generates a request for the GetBucketTagging operation. -func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *aws.Request, output *GetBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketTagging == nil { - opGetBucketTagging = &aws.Operation{ - Name: "GetBucketTagging", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?tagging", - } - } - - if input == nil { - input = &GetBucketTaggingInput{} - } - - req = c.newRequest(opGetBucketTagging, input, output) - output = &GetBucketTaggingOutput{} - req.Data = output - return -} - -// Returns the tag set associated with the bucket. -func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (output *GetBucketTaggingOutput, err error) { - req, out := c.GetBucketTaggingRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketTagging *aws.Operation - -// GetBucketVersioningRequest generates a request for the GetBucketVersioning operation. -func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *aws.Request, output *GetBucketVersioningOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketVersioning == nil { - opGetBucketVersioning = &aws.Operation{ - Name: "GetBucketVersioning", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versioning", - } - } - - if input == nil { - input = &GetBucketVersioningInput{} - } - - req = c.newRequest(opGetBucketVersioning, input, output) - output = &GetBucketVersioningOutput{} - req.Data = output - return -} - -// Returns the versioning state of a bucket. -func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (output *GetBucketVersioningOutput, err error) { - req, out := c.GetBucketVersioningRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketVersioning *aws.Operation - -// GetBucketWebsiteRequest generates a request for the GetBucketWebsite operation. -func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *aws.Request, output *GetBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketWebsite == nil { - opGetBucketWebsite = &aws.Operation{ - Name: "GetBucketWebsite", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?website", - } - } - - if input == nil { - input = &GetBucketWebsiteInput{} - } - - req = c.newRequest(opGetBucketWebsite, input, output) - output = &GetBucketWebsiteOutput{} - req.Data = output - return -} - -// Returns the website configuration for a bucket. -func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (output *GetBucketWebsiteOutput, err error) { - req, out := c.GetBucketWebsiteRequest(input) - output = out - err = req.Send() - return -} - -var opGetBucketWebsite *aws.Operation - -// GetObjectRequest generates a request for the GetObject operation. -func (c *S3) GetObjectRequest(input *GetObjectInput) (req *aws.Request, output *GetObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObject == nil { - opGetObject = &aws.Operation{ - Name: "GetObject", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &GetObjectInput{} - } - - req = c.newRequest(opGetObject, input, output) - output = &GetObjectOutput{} - req.Data = output - return -} - -// Retrieves objects from Amazon S3. -func (c *S3) GetObject(input *GetObjectInput) (output *GetObjectOutput, err error) { - req, out := c.GetObjectRequest(input) - output = out - err = req.Send() - return -} - -var opGetObject *aws.Operation - -// GetObjectACLRequest generates a request for the GetObjectACL operation. -func (c *S3) GetObjectACLRequest(input *GetObjectACLInput) (req *aws.Request, output *GetObjectACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObjectACL == nil { - opGetObjectACL = &aws.Operation{ - Name: "GetObjectAcl", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?acl", - } - } - - if input == nil { - input = &GetObjectACLInput{} - } - - req = c.newRequest(opGetObjectACL, input, output) - output = &GetObjectACLOutput{} - req.Data = output - return -} - -// Returns the access control list (ACL) of an object. -func (c *S3) GetObjectACL(input *GetObjectACLInput) (output *GetObjectACLOutput, err error) { - req, out := c.GetObjectACLRequest(input) - output = out - err = req.Send() - return -} - -var opGetObjectACL *aws.Operation - -// GetObjectTorrentRequest generates a request for the GetObjectTorrent operation. -func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *aws.Request, output *GetObjectTorrentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObjectTorrent == nil { - opGetObjectTorrent = &aws.Operation{ - Name: "GetObjectTorrent", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?torrent", - } - } - - if input == nil { - input = &GetObjectTorrentInput{} - } - - req = c.newRequest(opGetObjectTorrent, input, output) - output = &GetObjectTorrentOutput{} - req.Data = output - return -} - -// Return torrent files from a bucket. -func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (output *GetObjectTorrentOutput, err error) { - req, out := c.GetObjectTorrentRequest(input) - output = out - err = req.Send() - return -} - -var opGetObjectTorrent *aws.Operation - -// HeadBucketRequest generates a request for the HeadBucket operation. -func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *aws.Request, output *HeadBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opHeadBucket == nil { - opHeadBucket = &aws.Operation{ - Name: "HeadBucket", - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}", - } - } - - if input == nil { - input = &HeadBucketInput{} - } - - req = c.newRequest(opHeadBucket, input, output) - output = &HeadBucketOutput{} - req.Data = output - return -} - -// This operation is useful to determine if a bucket exists and you have permission -// to access it. -func (c *S3) HeadBucket(input *HeadBucketInput) (output *HeadBucketOutput, err error) { - req, out := c.HeadBucketRequest(input) - output = out - err = req.Send() - return -} - -var opHeadBucket *aws.Operation - -// HeadObjectRequest generates a request for the HeadObject operation. -func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *aws.Request, output *HeadObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opHeadObject == nil { - opHeadObject = &aws.Operation{ - Name: "HeadObject", - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &HeadObjectInput{} - } - - req = c.newRequest(opHeadObject, input, output) - output = &HeadObjectOutput{} - req.Data = output - return -} - -// The HEAD operation retrieves metadata from an object without returning the -// object itself. This operation is useful if you're only interested in an object's -// metadata. To use HEAD, you must have READ access to the object. -func (c *S3) HeadObject(input *HeadObjectInput) (output *HeadObjectOutput, err error) { - req, out := c.HeadObjectRequest(input) - output = out - err = req.Send() - return -} - -var opHeadObject *aws.Operation - -// ListBucketsRequest generates a request for the ListBuckets operation. -func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *aws.Request, output *ListBucketsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListBuckets == nil { - opListBuckets = &aws.Operation{ - Name: "ListBuckets", - HTTPMethod: "GET", - HTTPPath: "/", - } - } - - if input == nil { - input = &ListBucketsInput{} - } - - req = c.newRequest(opListBuckets, input, output) - output = &ListBucketsOutput{} - req.Data = output - return -} - -// Returns a list of all buckets owned by the authenticated sender of the request. -func (c *S3) ListBuckets(input *ListBucketsInput) (output *ListBucketsOutput, err error) { - req, out := c.ListBucketsRequest(input) - output = out - err = req.Send() - return -} - -var opListBuckets *aws.Operation - -// ListMultipartUploadsRequest generates a request for the ListMultipartUploads operation. -func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *aws.Request, output *ListMultipartUploadsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListMultipartUploads == nil { - opListMultipartUploads = &aws.Operation{ - Name: "ListMultipartUploads", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?uploads", - } - } - - if input == nil { - input = &ListMultipartUploadsInput{} - } - - req = c.newRequest(opListMultipartUploads, input, output) - output = &ListMultipartUploadsOutput{} - req.Data = output - return -} - -// This operation lists in-progress multipart uploads. -func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (output *ListMultipartUploadsOutput, err error) { - req, out := c.ListMultipartUploadsRequest(input) - output = out - err = req.Send() - return -} - -var opListMultipartUploads *aws.Operation - -// ListObjectVersionsRequest generates a request for the ListObjectVersions operation. -func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *aws.Request, output *ListObjectVersionsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListObjectVersions == nil { - opListObjectVersions = &aws.Operation{ - Name: "ListObjectVersions", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versions", - } - } - - if input == nil { - input = &ListObjectVersionsInput{} - } - - req = c.newRequest(opListObjectVersions, input, output) - output = &ListObjectVersionsOutput{} - req.Data = output - return -} - -// Returns metadata about all of the versions of objects in a bucket. -func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (output *ListObjectVersionsOutput, err error) { - req, out := c.ListObjectVersionsRequest(input) - output = out - err = req.Send() - return -} - -var opListObjectVersions *aws.Operation - -// ListObjectsRequest generates a request for the ListObjects operation. -func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *aws.Request, output *ListObjectsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListObjects == nil { - opListObjects = &aws.Operation{ - Name: "ListObjects", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}", - } - } - - if input == nil { - input = &ListObjectsInput{} - } - - req = c.newRequest(opListObjects, input, output) - output = &ListObjectsOutput{} - req.Data = output - return -} - -// Returns some or all (up to 1000) of the objects in a bucket. You can use -// the request parameters as selection criteria to return a subset of the objects -// in a bucket. -func (c *S3) ListObjects(input *ListObjectsInput) (output *ListObjectsOutput, err error) { - req, out := c.ListObjectsRequest(input) - output = out - err = req.Send() - return -} - -var opListObjects *aws.Operation - -// ListPartsRequest generates a request for the ListParts operation. -func (c *S3) ListPartsRequest(input *ListPartsInput) (req *aws.Request, output *ListPartsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListParts == nil { - opListParts = &aws.Operation{ - Name: "ListParts", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &ListPartsInput{} - } - - req = c.newRequest(opListParts, input, output) - output = &ListPartsOutput{} - req.Data = output - return -} - -// Lists the parts that have been uploaded for a specific multipart upload. -func (c *S3) ListParts(input *ListPartsInput) (output *ListPartsOutput, err error) { - req, out := c.ListPartsRequest(input) - output = out - err = req.Send() - return -} - -var opListParts *aws.Operation - -// PutBucketACLRequest generates a request for the PutBucketACL operation. -func (c *S3) PutBucketACLRequest(input *PutBucketACLInput) (req *aws.Request, output *PutBucketACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketACL == nil { - opPutBucketACL = &aws.Operation{ - Name: "PutBucketAcl", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?acl", - } - } - - if input == nil { - input = &PutBucketACLInput{} - } - - req = c.newRequest(opPutBucketACL, input, output) - output = &PutBucketACLOutput{} - req.Data = output - return -} - -// Sets the permissions on a bucket using access control lists (ACL). -func (c *S3) PutBucketACL(input *PutBucketACLInput) (output *PutBucketACLOutput, err error) { - req, out := c.PutBucketACLRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketACL *aws.Operation - -// PutBucketCORSRequest generates a request for the PutBucketCORS operation. -func (c *S3) PutBucketCORSRequest(input *PutBucketCORSInput) (req *aws.Request, output *PutBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketCORS == nil { - opPutBucketCORS = &aws.Operation{ - Name: "PutBucketCors", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?cors", - } - } - - if input == nil { - input = &PutBucketCORSInput{} - } - - req = c.newRequest(opPutBucketCORS, input, output) - output = &PutBucketCORSOutput{} - req.Data = output - return -} - -// Sets the cors configuration for a bucket. -func (c *S3) PutBucketCORS(input *PutBucketCORSInput) (output *PutBucketCORSOutput, err error) { - req, out := c.PutBucketCORSRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketCORS *aws.Operation - -// PutBucketLifecycleRequest generates a request for the PutBucketLifecycle operation. -func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *aws.Request, output *PutBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketLifecycle == nil { - opPutBucketLifecycle = &aws.Operation{ - Name: "PutBucketLifecycle", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?lifecycle", - } - } - - if input == nil { - input = &PutBucketLifecycleInput{} - } - - req = c.newRequest(opPutBucketLifecycle, input, output) - output = &PutBucketLifecycleOutput{} - req.Data = output - return -} - -// Sets lifecycle configuration for your bucket. If a lifecycle configuration -// exists, it replaces it. -func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (output *PutBucketLifecycleOutput, err error) { - req, out := c.PutBucketLifecycleRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketLifecycle *aws.Operation - -// PutBucketLoggingRequest generates a request for the PutBucketLogging operation. -func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *aws.Request, output *PutBucketLoggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketLogging == nil { - opPutBucketLogging = &aws.Operation{ - Name: "PutBucketLogging", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?logging", - } - } - - if input == nil { - input = &PutBucketLoggingInput{} - } - - req = c.newRequest(opPutBucketLogging, input, output) - output = &PutBucketLoggingOutput{} - req.Data = output - return -} - -// Set the logging parameters for a bucket and to specify permissions for who -// can view and modify the logging parameters. To set the logging status of -// a bucket, you must be the bucket owner. -func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (output *PutBucketLoggingOutput, err error) { - req, out := c.PutBucketLoggingRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketLogging *aws.Operation - -// PutBucketNotificationRequest generates a request for the PutBucketNotification operation. -func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *aws.Request, output *PutBucketNotificationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketNotification == nil { - opPutBucketNotification = &aws.Operation{ - Name: "PutBucketNotification", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?notification", - } - } - - if input == nil { - input = &PutBucketNotificationInput{} - } - - req = c.newRequest(opPutBucketNotification, input, output) - output = &PutBucketNotificationOutput{} - req.Data = output - return -} - -// Enables notifications of specified events for a bucket. -func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (output *PutBucketNotificationOutput, err error) { - req, out := c.PutBucketNotificationRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketNotification *aws.Operation - -// PutBucketPolicyRequest generates a request for the PutBucketPolicy operation. -func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *aws.Request, output *PutBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketPolicy == nil { - opPutBucketPolicy = &aws.Operation{ - Name: "PutBucketPolicy", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?policy", - } - } - - if input == nil { - input = &PutBucketPolicyInput{} - } - - req = c.newRequest(opPutBucketPolicy, input, output) - output = &PutBucketPolicyOutput{} - req.Data = output - return -} - -// Replaces a policy on a bucket. If the bucket already has a policy, the one -// in this request completely replaces it. -func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (output *PutBucketPolicyOutput, err error) { - req, out := c.PutBucketPolicyRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketPolicy *aws.Operation - -// PutBucketReplicationRequest generates a request for the PutBucketReplication operation. -func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *aws.Request, output *PutBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketReplication == nil { - opPutBucketReplication = &aws.Operation{ - Name: "PutBucketReplication", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?replication", - } - } - - if input == nil { - input = &PutBucketReplicationInput{} - } - - req = c.newRequest(opPutBucketReplication, input, output) - output = &PutBucketReplicationOutput{} - req.Data = output - return -} - -// Creates a new replication configuration (or replaces an existing one, if -// present). -func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (output *PutBucketReplicationOutput, err error) { - req, out := c.PutBucketReplicationRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketReplication *aws.Operation - -// PutBucketRequestPaymentRequest generates a request for the PutBucketRequestPayment operation. -func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *aws.Request, output *PutBucketRequestPaymentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketRequestPayment == nil { - opPutBucketRequestPayment = &aws.Operation{ - Name: "PutBucketRequestPayment", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?requestPayment", - } - } - - if input == nil { - input = &PutBucketRequestPaymentInput{} - } - - req = c.newRequest(opPutBucketRequestPayment, input, output) - output = &PutBucketRequestPaymentOutput{} - req.Data = output - return -} - -// Sets the request payment configuration for a bucket. By default, the bucket -// owner pays for downloads from the bucket. This configuration parameter enables -// the bucket owner (only) to specify that the person requesting the download -// will be charged for the download. Documentation on requester pays buckets -// can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/RequesterPaysBuckets.html -func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (output *PutBucketRequestPaymentOutput, err error) { - req, out := c.PutBucketRequestPaymentRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketRequestPayment *aws.Operation - -// PutBucketTaggingRequest generates a request for the PutBucketTagging operation. -func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *aws.Request, output *PutBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketTagging == nil { - opPutBucketTagging = &aws.Operation{ - Name: "PutBucketTagging", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?tagging", - } - } - - if input == nil { - input = &PutBucketTaggingInput{} - } - - req = c.newRequest(opPutBucketTagging, input, output) - output = &PutBucketTaggingOutput{} - req.Data = output - return -} - -// Sets the tags for a bucket. -func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (output *PutBucketTaggingOutput, err error) { - req, out := c.PutBucketTaggingRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketTagging *aws.Operation - -// PutBucketVersioningRequest generates a request for the PutBucketVersioning operation. -func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *aws.Request, output *PutBucketVersioningOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketVersioning == nil { - opPutBucketVersioning = &aws.Operation{ - Name: "PutBucketVersioning", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?versioning", - } - } - - if input == nil { - input = &PutBucketVersioningInput{} - } - - req = c.newRequest(opPutBucketVersioning, input, output) - output = &PutBucketVersioningOutput{} - req.Data = output - return -} - -// Sets the versioning state of an existing bucket. To set the versioning state, -// you must be the bucket owner. -func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (output *PutBucketVersioningOutput, err error) { - req, out := c.PutBucketVersioningRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketVersioning *aws.Operation - -// PutBucketWebsiteRequest generates a request for the PutBucketWebsite operation. -func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *aws.Request, output *PutBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketWebsite == nil { - opPutBucketWebsite = &aws.Operation{ - Name: "PutBucketWebsite", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?website", - } - } - - if input == nil { - input = &PutBucketWebsiteInput{} - } - - req = c.newRequest(opPutBucketWebsite, input, output) - output = &PutBucketWebsiteOutput{} - req.Data = output - return -} - -// Set the website configuration for a bucket. -func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (output *PutBucketWebsiteOutput, err error) { - req, out := c.PutBucketWebsiteRequest(input) - output = out - err = req.Send() - return -} - -var opPutBucketWebsite *aws.Operation - -// PutObjectRequest generates a request for the PutObject operation. -func (c *S3) PutObjectRequest(input *PutObjectInput) (req *aws.Request, output *PutObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutObject == nil { - opPutObject = &aws.Operation{ - Name: "PutObject", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &PutObjectInput{} - } - - req = c.newRequest(opPutObject, input, output) - output = &PutObjectOutput{} - req.Data = output - return -} - -// Adds an object to a bucket. -func (c *S3) PutObject(input *PutObjectInput) (output *PutObjectOutput, err error) { - req, out := c.PutObjectRequest(input) - output = out - err = req.Send() - return -} - -var opPutObject *aws.Operation - -// PutObjectACLRequest generates a request for the PutObjectACL operation. -func (c *S3) PutObjectACLRequest(input *PutObjectACLInput) (req *aws.Request, output *PutObjectACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutObjectACL == nil { - opPutObjectACL = &aws.Operation{ - Name: "PutObjectAcl", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}?acl", - } - } - - if input == nil { - input = &PutObjectACLInput{} - } - - req = c.newRequest(opPutObjectACL, input, output) - output = &PutObjectACLOutput{} - req.Data = output - return -} - -// uses the acl subresource to set the access control list (ACL) permissions -// for an object that already exists in a bucket -func (c *S3) PutObjectACL(input *PutObjectACLInput) (output *PutObjectACLOutput, err error) { - req, out := c.PutObjectACLRequest(input) - output = out - err = req.Send() - return -} - -var opPutObjectACL *aws.Operation - -// RestoreObjectRequest generates a request for the RestoreObject operation. -func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *aws.Request, output *RestoreObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opRestoreObject == nil { - opRestoreObject = &aws.Operation{ - Name: "RestoreObject", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?restore", - } - } - - if input == nil { - input = &RestoreObjectInput{} - } - - req = c.newRequest(opRestoreObject, input, output) - output = &RestoreObjectOutput{} - req.Data = output - return -} - -// Restores an archived copy of an object back into Amazon S3 -func (c *S3) RestoreObject(input *RestoreObjectInput) (output *RestoreObjectOutput, err error) { - req, out := c.RestoreObjectRequest(input) - output = out - err = req.Send() - return -} - -var opRestoreObject *aws.Operation - -// UploadPartRequest generates a request for the UploadPart operation. -func (c *S3) UploadPartRequest(input *UploadPartInput) (req *aws.Request, output *UploadPartOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opUploadPart == nil { - opUploadPart = &aws.Operation{ - Name: "UploadPart", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &UploadPartInput{} - } - - req = c.newRequest(opUploadPart, input, output) - output = &UploadPartOutput{} - req.Data = output - return -} - -// Uploads a part in a multipart upload. -// -// Note: After you initiate multipart upload and upload one or more parts, -// you must either complete or abort multipart upload in order to stop getting -// charged for storage of the uploaded parts. Only after you either complete -// or abort multipart upload, Amazon S3 frees up the parts storage and stops -// charging you for the parts storage. -func (c *S3) UploadPart(input *UploadPartInput) (output *UploadPartOutput, err error) { - req, out := c.UploadPartRequest(input) - output = out - err = req.Send() - return -} - -var opUploadPart *aws.Operation - -// UploadPartCopyRequest generates a request for the UploadPartCopy operation. -func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *aws.Request, output *UploadPartCopyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opUploadPartCopy == nil { - opUploadPartCopy = &aws.Operation{ - Name: "UploadPartCopy", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - } - - if input == nil { - input = &UploadPartCopyInput{} - } - - req = c.newRequest(opUploadPartCopy, input, output) - output = &UploadPartCopyOutput{} - req.Data = output - return -} - -// Uploads a part by copying data from an existing object as data source. -func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (output *UploadPartCopyOutput, err error) { - req, out := c.UploadPartCopyRequest(input) - output = out - err = req.Send() - return -} - -var opUploadPartCopy *aws.Operation - -type AbortMultipartUploadInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - UploadID *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` - - metadataAbortMultipartUploadInput `json:"-", xml:"-"` -} - -type metadataAbortMultipartUploadInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type AbortMultipartUploadOutput struct { - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataAbortMultipartUploadOutput `json:"-", xml:"-"` -} - -type metadataAbortMultipartUploadOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type AccessControlPolicy struct { - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` - - metadataAccessControlPolicy `json:"-", xml:"-"` -} - -type metadataAccessControlPolicy struct { - SDKShapeTraits bool `type:"structure"` -} - -type Bucket struct { - // Date the bucket was created. - CreationDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // The name of the bucket. - Name *string `type:"string"` - - metadataBucket `json:"-", xml:"-"` -} - -type metadataBucket struct { - SDKShapeTraits bool `type:"structure"` -} - -type BucketLoggingStatus struct { - LoggingEnabled *LoggingEnabled `type:"structure"` - - metadataBucketLoggingStatus `json:"-", xml:"-"` -} - -type metadataBucketLoggingStatus struct { - SDKShapeTraits bool `type:"structure"` -} - -type CORSConfiguration struct { - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` - - metadataCORSConfiguration `json:"-", xml:"-"` -} - -type metadataCORSConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type CORSRule struct { - // Specifies which headers are allowed in a pre-flight OPTIONS request. - AllowedHeaders []*string `locationName:"AllowedHeader" type:"list" flattened:"true"` - - // Identifies HTTP methods that the domain/origin specified in the rule is allowed - // to execute. - AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true"` - - // One or more origins you want customers to be able to access the bucket from. - AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true"` - - // One or more headers in the response that you want customers to be able to - // access from their applications (for example, from a JavaScript XMLHttpRequest - // object). - ExposeHeaders []*string `locationName:"ExposeHeader" type:"list" flattened:"true"` - - // The time in seconds that your browser is to cache the preflight response - // for the specified resource. - MaxAgeSeconds *int64 `type:"integer"` - - metadataCORSRule `json:"-", xml:"-"` -} - -type metadataCORSRule struct { - SDKShapeTraits bool `type:"structure"` -} - -type CloudFunctionConfiguration struct { - CloudFunction *string `type:"string"` - - Event *string `type:"string"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - ID *string `locationName:"Id" type:"string"` - - InvocationRole *string `type:"string"` - - metadataCloudFunctionConfiguration `json:"-", xml:"-"` -} - -type metadataCloudFunctionConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type CommonPrefix struct { - Prefix *string `type:"string"` - - metadataCommonPrefix `json:"-", xml:"-"` -} - -type metadataCommonPrefix struct { - SDKShapeTraits bool `type:"structure"` -} - -type CompleteMultipartUploadInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - MultipartUpload *CompletedMultipartUpload `locationName:"CompleteMultipartUpload" type:"structure"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - UploadID *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` - - metadataCompleteMultipartUploadInput `json:"-", xml:"-"` -} - -type metadataCompleteMultipartUploadInput struct { - SDKShapeTraits bool `type:"structure" payload:"MultipartUpload"` -} - -type CompleteMultipartUploadOutput struct { - Bucket *string `type:"string"` - - // Entity tag of the object. - ETag *string `type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - Key *string `type:"string"` - - Location *string `type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // Version of the object. - VersionID *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - metadataCompleteMultipartUploadOutput `json:"-", xml:"-"` -} - -type metadataCompleteMultipartUploadOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type CompletedMultipartUpload struct { - Parts []*CompletedPart `locationName:"Part" type:"list" flattened:"true"` - - metadataCompletedMultipartUpload `json:"-", xml:"-"` -} - -type metadataCompletedMultipartUpload struct { - SDKShapeTraits bool `type:"structure"` -} - -type CompletedPart struct { - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` - - // Part number that identifies the part. - PartNumber *int64 `type:"integer"` - - metadataCompletedPart `json:"-", xml:"-"` -} - -type metadataCompletedPart struct { - SDKShapeTraits bool `type:"structure"` -} - -type Condition struct { - // The HTTP error code when the redirect is applied. In the event of an error, - // if the error code equals this value, then the specified redirect is applied. - // Required when parent element Condition is specified and sibling KeyPrefixEquals - // is not specified. If both are specified, then both must be true for the redirect - // to be applied. - HTTPErrorCodeReturnedEquals *string `locationName:"HttpErrorCodeReturnedEquals" type:"string"` - - // The object key name prefix when the redirect is applied. For example, to - // redirect requests for ExamplePage.html, the key prefix will be ExamplePage.html. - // To redirect request for all pages with the prefix docs/, the key prefix will - // be /docs, which identifies all objects in the docs/ folder. Required when - // the parent element Condition is specified and sibling HttpErrorCodeReturnedEquals - // is not specified. If both conditions are specified, both must be true for - // the redirect to be applied. - KeyPrefixEquals *string `type:"string"` - - metadataCondition `json:"-", xml:"-"` -} - -type metadataCondition struct { - SDKShapeTraits bool `type:"structure"` -} - -type CopyObjectInput struct { - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. - CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` - - // Copies the object if its entity tag (ETag) matches the specified tag. - CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` - - // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Copies the object if its entity tag (ETag) is different than the specified - // ETag. - CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` - - // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Specifies the algorithm to use when decrypting the source object (e.g., AES256). - CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt - // the source object. The encryption key provided in this header must be one - // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata *map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Specifies whether the metadata is copied from the source object or replaced - // with metadata provided in the request. - MetadataDirective *string `location:"header" locationName:"x-amz-metadata-directive" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` - - metadataCopyObjectInput `json:"-", xml:"-"` -} - -type metadataCopyObjectInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type CopyObjectOutput struct { - CopyObjectResult *CopyObjectResult `type:"structure"` - - CopySourceVersionID *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` - - // If the object expiration is configured, the response includes this header. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - metadataCopyObjectOutput `json:"-", xml:"-"` -} - -type metadataCopyObjectOutput struct { - SDKShapeTraits bool `type:"structure" payload:"CopyObjectResult"` -} - -type CopyObjectResult struct { - ETag *string `type:"string"` - - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataCopyObjectResult `json:"-", xml:"-"` -} - -type metadataCopyObjectResult struct { - SDKShapeTraits bool `type:"structure"` -} - -type CopyPartResult struct { - // Entity tag of the object. - ETag *string `type:"string"` - - // Date and time at which the object was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataCopyPartResult `json:"-", xml:"-"` -} - -type metadataCopyPartResult struct { - SDKShapeTraits bool `type:"structure"` -} - -type CreateBucketConfiguration struct { - // Specifies the region where the bucket will be created. - LocationConstraint *string `type:"string"` - - metadataCreateBucketConfiguration `json:"-", xml:"-"` -} - -type metadataCreateBucketConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type CreateBucketInput struct { - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - CreateBucketConfiguration *CreateBucketConfiguration `locationName:"CreateBucketConfiguration" type:"structure"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - metadataCreateBucketInput `json:"-", xml:"-"` -} - -type metadataCreateBucketInput struct { - SDKShapeTraits bool `type:"structure" payload:"CreateBucketConfiguration"` -} - -type CreateBucketOutput struct { - Location *string `location:"header" locationName:"Location" type:"string"` - - metadataCreateBucketOutput `json:"-", xml:"-"` -} - -type metadataCreateBucketOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type CreateMultipartUploadInput struct { - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata *map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` - - metadataCreateMultipartUploadInput `json:"-", xml:"-"` -} - -type metadataCreateMultipartUploadInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type CreateMultipartUploadOutput struct { - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `locationName:"Bucket" type:"string"` - - // Object key for which the multipart upload was initiated. - Key *string `type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // ID for the initiated multipart upload. - UploadID *string `locationName:"UploadId" type:"string"` - - metadataCreateMultipartUploadOutput `json:"-", xml:"-"` -} - -type metadataCreateMultipartUploadOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type Delete struct { - Objects []*ObjectIdentifier `locationName:"Object" type:"list" flattened:"true" required:"true"` - - // Element to enable quiet mode for the request. When you add this element, - // you must set its value to true. - Quiet *bool `type:"boolean"` - - metadataDelete `json:"-", xml:"-"` -} - -type metadataDelete struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketCORSInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketCORSInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketCORSInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketCORSOutput struct { - metadataDeleteBucketCORSOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketCORSOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketLifecycleInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketLifecycleInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketLifecycleInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketLifecycleOutput struct { - metadataDeleteBucketLifecycleOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketLifecycleOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketOutput struct { - metadataDeleteBucketOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketPolicyInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketPolicyInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketPolicyInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketPolicyOutput struct { - metadataDeleteBucketPolicyOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketPolicyOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketReplicationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketReplicationInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketReplicationInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketReplicationOutput struct { - metadataDeleteBucketReplicationOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketReplicationOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketTaggingInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketTaggingInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketTaggingInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketTaggingOutput struct { - metadataDeleteBucketTaggingOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketTaggingOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketWebsiteInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataDeleteBucketWebsiteInput `json:"-", xml:"-"` -} - -type metadataDeleteBucketWebsiteInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteBucketWebsiteOutput struct { - metadataDeleteBucketWebsiteOutput `json:"-", xml:"-"` -} - -type metadataDeleteBucketWebsiteOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteMarkerEntry struct { - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - // Version ID of an object. - VersionID *string `locationName:"VersionId" type:"string"` - - metadataDeleteMarkerEntry `json:"-", xml:"-"` -} - -type metadataDeleteMarkerEntry struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteObjectInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionID *string `location:"querystring" locationName:"versionId" type:"string"` - - metadataDeleteObjectInput `json:"-", xml:"-"` -} - -type metadataDeleteObjectInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteObjectOutput struct { - // Specifies whether the versioned object that was permanently deleted was (true) - // or was not (false) a delete marker. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // Returns the version ID of the delete marker created as a result of the DELETE - // operation. - VersionID *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - metadataDeleteObjectOutput `json:"-", xml:"-"` -} - -type metadataDeleteObjectOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeleteObjectsInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Delete *Delete `locationName:"Delete" type:"structure" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - metadataDeleteObjectsInput `json:"-", xml:"-"` -} - -type metadataDeleteObjectsInput struct { - SDKShapeTraits bool `type:"structure" payload:"Delete"` -} - -type DeleteObjectsOutput struct { - Deleted []*DeletedObject `type:"list" flattened:"true"` - - Errors []*Error `locationName:"Error" type:"list" flattened:"true"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataDeleteObjectsOutput `json:"-", xml:"-"` -} - -type metadataDeleteObjectsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type DeletedObject struct { - DeleteMarker *bool `type:"boolean"` - - DeleteMarkerVersionID *string `locationName:"DeleteMarkerVersionId" type:"string"` - - Key *string `type:"string"` - - VersionID *string `locationName:"VersionId" type:"string"` - - metadataDeletedObject `json:"-", xml:"-"` -} - -type metadataDeletedObject struct { - SDKShapeTraits bool `type:"structure"` -} - -type Destination struct { - // Amazon resource name (ARN) of the bucket where you want Amazon S3 to store - // replicas of the object identified by the rule. - Bucket *string `type:"string" required:"true"` - - metadataDestination `json:"-", xml:"-"` -} - -type metadataDestination struct { - SDKShapeTraits bool `type:"structure"` -} - -type Error struct { - Code *string `type:"string"` - - Key *string `type:"string"` - - Message *string `type:"string"` - - VersionID *string `locationName:"VersionId" type:"string"` - - metadataError `json:"-", xml:"-"` -} - -type metadataError struct { - SDKShapeTraits bool `type:"structure"` -} - -type ErrorDocument struct { - // The object key name to use when a 4XX class error occurs. - Key *string `type:"string" required:"true"` - - metadataErrorDocument `json:"-", xml:"-"` -} - -type metadataErrorDocument struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketACLInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketACLInput `json:"-", xml:"-"` -} - -type metadataGetBucketACLInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketACLOutput struct { - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` - - metadataGetBucketACLOutput `json:"-", xml:"-"` -} - -type metadataGetBucketACLOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketCORSInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketCORSInput `json:"-", xml:"-"` -} - -type metadataGetBucketCORSInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketCORSOutput struct { - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` - - metadataGetBucketCORSOutput `json:"-", xml:"-"` -} - -type metadataGetBucketCORSOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLifecycleInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketLifecycleInput `json:"-", xml:"-"` -} - -type metadataGetBucketLifecycleInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLifecycleOutput struct { - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` - - metadataGetBucketLifecycleOutput `json:"-", xml:"-"` -} - -type metadataGetBucketLifecycleOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLocationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketLocationInput `json:"-", xml:"-"` -} - -type metadataGetBucketLocationInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLocationOutput struct { - LocationConstraint *string `type:"string"` - - metadataGetBucketLocationOutput `json:"-", xml:"-"` -} - -type metadataGetBucketLocationOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLoggingInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketLoggingInput `json:"-", xml:"-"` -} - -type metadataGetBucketLoggingInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketLoggingOutput struct { - LoggingEnabled *LoggingEnabled `type:"structure"` - - metadataGetBucketLoggingOutput `json:"-", xml:"-"` -} - -type metadataGetBucketLoggingOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketNotificationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketNotificationInput `json:"-", xml:"-"` -} - -type metadataGetBucketNotificationInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketNotificationOutput struct { - CloudFunctionConfiguration *CloudFunctionConfiguration `type:"structure"` - - QueueConfiguration *QueueConfiguration `type:"structure"` - - TopicConfiguration *TopicConfiguration `type:"structure"` - - metadataGetBucketNotificationOutput `json:"-", xml:"-"` -} - -type metadataGetBucketNotificationOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketPolicyInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketPolicyInput `json:"-", xml:"-"` -} - -type metadataGetBucketPolicyInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketPolicyOutput struct { - // The bucket policy as a JSON document. - Policy *string `type:"string"` - - metadataGetBucketPolicyOutput `json:"-", xml:"-"` -} - -type metadataGetBucketPolicyOutput struct { - SDKShapeTraits bool `type:"structure" payload:"Policy"` -} - -type GetBucketReplicationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketReplicationInput `json:"-", xml:"-"` -} - -type metadataGetBucketReplicationInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketReplicationOutput struct { - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - ReplicationConfiguration *ReplicationConfiguration `type:"structure"` - - metadataGetBucketReplicationOutput `json:"-", xml:"-"` -} - -type metadataGetBucketReplicationOutput struct { - SDKShapeTraits bool `type:"structure" payload:"ReplicationConfiguration"` -} - -type GetBucketRequestPaymentInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketRequestPaymentInput `json:"-", xml:"-"` -} - -type metadataGetBucketRequestPaymentInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketRequestPaymentOutput struct { - // Specifies who pays for the download and request fees. - Payer *string `type:"string"` - - metadataGetBucketRequestPaymentOutput `json:"-", xml:"-"` -} - -type metadataGetBucketRequestPaymentOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketTaggingInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketTaggingInput `json:"-", xml:"-"` -} - -type metadataGetBucketTaggingInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketTaggingOutput struct { - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` - - metadataGetBucketTaggingOutput `json:"-", xml:"-"` -} - -type metadataGetBucketTaggingOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketVersioningInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketVersioningInput `json:"-", xml:"-"` -} - -type metadataGetBucketVersioningInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketVersioningOutput struct { - // Specifies whether MFA delete is enabled in the bucket versioning configuration. - // This element is only returned if the bucket has been configured with MFA - // delete. If the bucket has never been so configured, this element is not returned. - MFADelete *string `locationName:"MfaDelete" type:"string"` - - // The versioning state of the bucket. - Status *string `type:"string"` - - metadataGetBucketVersioningOutput `json:"-", xml:"-"` -} - -type metadataGetBucketVersioningOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketWebsiteInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataGetBucketWebsiteInput `json:"-", xml:"-"` -} - -type metadataGetBucketWebsiteInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetBucketWebsiteOutput struct { - ErrorDocument *ErrorDocument `type:"structure"` - - IndexDocument *IndexDocument `type:"structure"` - - RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - - RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` - - metadataGetBucketWebsiteOutput `json:"-", xml:"-"` -} - -type metadataGetBucketWebsiteOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetObjectACLInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionID *string `location:"querystring" locationName:"versionId" type:"string"` - - metadataGetObjectACLInput `json:"-", xml:"-"` -} - -type metadataGetObjectACLInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetObjectACLOutput struct { - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataGetObjectACLOutput `json:"-", xml:"-"` -} - -type metadataGetObjectACLOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetObjectInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` - - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` - - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Sets the Cache-Control header of the response. - ResponseCacheControl *string `location:"querystring" locationName:"response-cache-control" type:"string"` - - // Sets the Content-Disposition header of the response - ResponseContentDisposition *string `location:"querystring" locationName:"response-content-disposition" type:"string"` - - // Sets the Content-Encoding header of the response. - ResponseContentEncoding *string `location:"querystring" locationName:"response-content-encoding" type:"string"` - - // Sets the Content-Language header of the response. - ResponseContentLanguage *string `location:"querystring" locationName:"response-content-language" type:"string"` - - // Sets the Content-Type header of the response. - ResponseContentType *string `location:"querystring" locationName:"response-content-type" type:"string"` - - // Sets the Expires header of the response. - ResponseExpires *time.Time `location:"querystring" locationName:"response-expires" type:"timestamp" timestampFormat:"iso8601"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionID *string `location:"querystring" locationName:"versionId" type:"string"` - - metadataGetObjectInput `json:"-", xml:"-"` -} - -type metadataGetObjectInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetObjectOutput struct { - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - - // Object data. - Body io.ReadCloser `type:"blob"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"integer"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` - - // A map of metadata to store with the object in S3. - Metadata *map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` - - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // Version of the object. - VersionID *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` - - metadataGetObjectOutput `json:"-", xml:"-"` -} - -type metadataGetObjectOutput struct { - SDKShapeTraits bool `type:"structure" payload:"Body"` -} - -type GetObjectTorrentInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - metadataGetObjectTorrentInput `json:"-", xml:"-"` -} - -type metadataGetObjectTorrentInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type GetObjectTorrentOutput struct { - Body io.ReadCloser `type:"blob"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataGetObjectTorrentOutput `json:"-", xml:"-"` -} - -type metadataGetObjectTorrentOutput struct { - SDKShapeTraits bool `type:"structure" payload:"Body"` -} - -type Grant struct { - Grantee *Grantee `type:"structure"` - - // Specifies the permission given to the grantee. - Permission *string `type:"string"` - - metadataGrant `json:"-", xml:"-"` -} - -type metadataGrant struct { - SDKShapeTraits bool `type:"structure"` -} - -type Grantee struct { - // Screen name of the grantee. - DisplayName *string `type:"string"` - - // Email address of the grantee. - EmailAddress *string `type:"string"` - - // The canonical user ID of the grantee. - ID *string `type:"string"` - - // Type of grantee - Type *string `locationName:"xsi:type" type:"string" required:"true"` - - // URI of the grantee group. - URI *string `type:"string"` - - metadataGrantee `json:"-", xml:"-"` -} - -type metadataGrantee struct { - SDKShapeTraits bool `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` -} - -type HeadBucketInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - metadataHeadBucketInput `json:"-", xml:"-"` -} - -type metadataHeadBucketInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type HeadBucketOutput struct { - metadataHeadBucketOutput `json:"-", xml:"-"` -} - -type metadataHeadBucketOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type HeadObjectInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` - - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` - - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionID *string `location:"querystring" locationName:"versionId" type:"string"` - - metadataHeadObjectInput `json:"-", xml:"-"` -} - -type metadataHeadObjectInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type HeadObjectOutput struct { - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"integer"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` - - // A map of metadata to store with the object in S3. - Metadata *map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` - - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // Version of the object. - VersionID *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` - - metadataHeadObjectOutput `json:"-", xml:"-"` -} - -type metadataHeadObjectOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type IndexDocument struct { - // A suffix that is appended to a request that is for a directory on the website - // endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ - // the data that is returned will be for the object with the key name images/index.html) - // The suffix must not be empty and must not include a slash character. - Suffix *string `type:"string" required:"true"` - - metadataIndexDocument `json:"-", xml:"-"` -} - -type metadataIndexDocument struct { - SDKShapeTraits bool `type:"structure"` -} - -type Initiator struct { - // Name of the Principal. - DisplayName *string `type:"string"` - - // If the principal is an AWS account, it provides the Canonical User ID. If - // the principal is an IAM User, it provides a user ARN value. - ID *string `type:"string"` - - metadataInitiator `json:"-", xml:"-"` -} - -type metadataInitiator struct { - SDKShapeTraits bool `type:"structure"` -} - -type LifecycleConfiguration struct { - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` - - metadataLifecycleConfiguration `json:"-", xml:"-"` -} - -type metadataLifecycleConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type LifecycleExpiration struct { - // Indicates at what date the object is to be moved or deleted. Should be in - // GMT ISO 8601 Format. - Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Indicates the lifetime, in days, of the objects that are subject to the rule. - // The value must be a non-zero positive integer. - Days *int64 `type:"integer"` - - metadataLifecycleExpiration `json:"-", xml:"-"` -} - -type metadataLifecycleExpiration struct { - SDKShapeTraits bool `type:"structure"` -} - -type LifecycleRule struct { - Expiration *LifecycleExpiration `type:"structure"` - - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` - - // Specifies when noncurrent object versions expire. Upon expiration, Amazon - // S3 permanently deletes the noncurrent object versions. You set this lifecycle - // configuration action on a bucket that has versioning enabled (or suspended) - // to request that Amazon S3 delete noncurrent object versions at a specific - // period in the object's lifetime. - NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` - - // Container for the transition rule that describes when noncurrent objects - // transition to the GLACIER storage class. If your bucket is versioning-enabled - // (or versioning is suspended), you can set this action to request that Amazon - // S3 transition noncurrent object versions to the GLACIER storage class at - // a specific period in the object's lifetime. - NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` - - // Prefix identifying one or more objects to which the rule applies. - Prefix *string `type:"string" required:"true"` - - // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule - // is not currently being applied. - Status *string `type:"string" required:"true"` - - Transition *Transition `type:"structure"` - - metadataLifecycleRule `json:"-", xml:"-"` -} - -type metadataLifecycleRule struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListBucketsInput struct { - metadataListBucketsInput `json:"-", xml:"-"` -} - -type metadataListBucketsInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListBucketsOutput struct { - Buckets []*Bucket `locationNameList:"Bucket" type:"list"` - - Owner *Owner `type:"structure"` - - metadataListBucketsOutput `json:"-", xml:"-"` -} - -type metadataListBucketsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListMultipartUploadsInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string"` - - // Together with upload-id-marker, this parameter specifies the multipart upload - // after which listing should begin. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - - // Sets the maximum number of multipart uploads, from 1 to 1,000, to return - // in the response body. 1,000 is the maximum number of uploads that can be - // returned in a response. - MaxUploads *int64 `location:"querystring" locationName:"max-uploads" type:"integer"` - - // Lists in-progress uploads only for those keys that begin with the specified - // prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Together with key-marker, specifies the multipart upload after which listing - // should begin. If key-marker is not specified, the upload-id-marker parameter - // is ignored. - UploadIDMarker *string `location:"querystring" locationName:"upload-id-marker" type:"string"` - - metadataListMultipartUploadsInput `json:"-", xml:"-"` -} - -type metadataListMultipartUploadsInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListMultipartUploadsOutput struct { - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` - - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string"` - - // Indicates whether the returned list of multipart uploads is truncated. A - // value of true indicates that the list was truncated. The list can be truncated - // if the number of multipart uploads exceeds the limit allowed or specified - // by max uploads. - IsTruncated *bool `type:"boolean"` - - // The key at or after which the listing began. - KeyMarker *string `type:"string"` - - // Maximum number of multipart uploads that could have been included in the - // response. - MaxUploads *int64 `type:"integer"` - - // When a list is truncated, this element specifies the value that should be - // used for the key-marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` - - // When a list is truncated, this element specifies the value that should be - // used for the upload-id-marker request parameter in a subsequent request. - NextUploadIDMarker *string `locationName:"NextUploadIdMarker" type:"string"` - - // When a prefix is provided in the request, this field contains the specified - // prefix. The result contains only keys starting with the specified prefix. - Prefix *string `type:"string"` - - // Upload ID after which listing began. - UploadIDMarker *string `locationName:"UploadIdMarker" type:"string"` - - Uploads []*MultipartUpload `locationName:"Upload" type:"list" flattened:"true"` - - metadataListMultipartUploadsOutput `json:"-", xml:"-"` -} - -type metadataListMultipartUploadsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListObjectVersionsInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string"` - - // Specifies the key to start with when listing objects in a bucket. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Specifies the object version you want to start listing from. - VersionIDMarker *string `location:"querystring" locationName:"version-id-marker" type:"string"` - - metadataListObjectVersionsInput `json:"-", xml:"-"` -} - -type metadataListObjectVersionsInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListObjectVersionsOutput struct { - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - DeleteMarkers []*DeleteMarkerEntry `locationName:"DeleteMarker" type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string"` - - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. If your results were truncated, you can - // make a follow-up paginated request using the NextKeyMarker and NextVersionIdMarker - // response parameters as a starting place in another request to return the - // rest of the results. - IsTruncated *bool `type:"boolean"` - - // Marks the last Key returned in a truncated response. - KeyMarker *string `type:"string"` - - MaxKeys *int64 `type:"integer"` - - Name *string `type:"string"` - - // Use this value for the key marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` - - // Use this value for the next version id marker parameter in a subsequent request. - NextVersionIDMarker *string `locationName:"NextVersionIdMarker" type:"string"` - - Prefix *string `type:"string"` - - VersionIDMarker *string `locationName:"VersionIdMarker" type:"string"` - - Versions []*ObjectVersion `locationName:"Version" type:"list" flattened:"true"` - - metadataListObjectVersionsOutput `json:"-", xml:"-"` -} - -type metadataListObjectVersionsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListObjectsInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string"` - - // Specifies the key to start with when listing objects in a bucket. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - metadataListObjectsInput `json:"-", xml:"-"` -} - -type metadataListObjectsInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListObjectsOutput struct { - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - Contents []*Object `type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string"` - - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. - IsTruncated *bool `type:"boolean"` - - Marker *string `type:"string"` - - MaxKeys *int64 `type:"integer"` - - Name *string `type:"string"` - - // When response is truncated (the IsTruncated element value in the response - // is true), you can use the key name in this field as marker in the subsequent - // request to get next set of objects. Amazon S3 lists objects in alphabetical - // order Note: This element is returned only if you have delimiter request parameter - // specified. If response does not include the NextMaker and it is truncated, - // you can use the value of the last Key in the response as the marker in the - // subsequent request to get the next set of object keys. - NextMarker *string `type:"string"` - - Prefix *string `type:"string"` - - metadataListObjectsOutput `json:"-", xml:"-"` -} - -type metadataListObjectsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListPartsInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Sets the maximum number of parts to return. - MaxParts *int64 `location:"querystring" locationName:"max-parts" type:"integer"` - - // Specifies the part after which listing should begin. Only parts with higher - // part numbers will be listed. - PartNumberMarker *int64 `location:"querystring" locationName:"part-number-marker" type:"integer"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Upload ID identifying the multipart upload whose parts are being listed. - UploadID *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` - - metadataListPartsInput `json:"-", xml:"-"` -} - -type metadataListPartsInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type ListPartsOutput struct { - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` - - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` - - // Indicates whether the returned list of parts is truncated. - IsTruncated *bool `type:"boolean"` - - // Object key for which the multipart upload was initiated. - Key *string `type:"string"` - - // Maximum number of parts that were allowed in the response. - MaxParts *int64 `type:"integer"` - - // When a list is truncated, this element specifies the last part in the list, - // as well as the value to use for the part-number-marker request parameter - // in a subsequent request. - NextPartNumberMarker *int64 `type:"integer"` - - Owner *Owner `type:"structure"` - - // Part number after which listing begins. - PartNumberMarker *int64 `type:"integer"` - - Parts []*Part `locationName:"Part" type:"list" flattened:"true"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - // Upload ID identifying the multipart upload whose parts are being listed. - UploadID *string `locationName:"UploadId" type:"string"` - - metadataListPartsOutput `json:"-", xml:"-"` -} - -type metadataListPartsOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type LoggingEnabled struct { - // Specifies the bucket where you want Amazon S3 to store server access logs. - // You can have your logs delivered to any bucket that you own, including the - // same bucket that is being logged. You can also configure multiple buckets - // to deliver their logs to the same target bucket. In this case you should - // choose a different TargetPrefix for each source bucket so that the delivered - // log files can be distinguished by key. - TargetBucket *string `type:"string"` - - TargetGrants []*TargetGrant `locationNameList:"Grant" type:"list"` - - // This element lets you specify a prefix for the keys that the log files will - // be stored under. - TargetPrefix *string `type:"string"` - - metadataLoggingEnabled `json:"-", xml:"-"` -} - -type metadataLoggingEnabled struct { - SDKShapeTraits bool `type:"structure"` -} - -type MultipartUpload struct { - // Date and time at which the multipart upload was initiated. - Initiated *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` - - // Key of the object for which the multipart upload was initiated. - Key *string `type:"string"` - - Owner *Owner `type:"structure"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - // Upload ID that identifies the multipart upload. - UploadID *string `locationName:"UploadId" type:"string"` - - metadataMultipartUpload `json:"-", xml:"-"` -} - -type metadataMultipartUpload struct { - SDKShapeTraits bool `type:"structure"` -} - -// Specifies when noncurrent object versions expire. Upon expiration, Amazon -// S3 permanently deletes the noncurrent object versions. You set this lifecycle -// configuration action on a bucket that has versioning enabled (or suspended) -// to request that Amazon S3 delete noncurrent object versions at a specific -// period in the object's lifetime. -type NoncurrentVersionExpiration struct { - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (/AmazonS3/latest/dev/s3-access-control.html) in the Amazon Simple Storage - // Service Developer Guide. - NoncurrentDays *int64 `type:"integer"` - - metadataNoncurrentVersionExpiration `json:"-", xml:"-"` -} - -type metadataNoncurrentVersionExpiration struct { - SDKShapeTraits bool `type:"structure"` -} - -// Container for the transition rule that describes when noncurrent objects -// transition to the GLACIER storage class. If your bucket is versioning-enabled -// (or versioning is suspended), you can set this action to request that Amazon -// S3 transition noncurrent object versions to the GLACIER storage class at -// a specific period in the object's lifetime. -type NoncurrentVersionTransition struct { - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (/AmazonS3/latest/dev/s3-access-control.html) in the Amazon Simple Storage - // Service Developer Guide. - NoncurrentDays *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - metadataNoncurrentVersionTransition `json:"-", xml:"-"` -} - -type metadataNoncurrentVersionTransition struct { - SDKShapeTraits bool `type:"structure"` -} - -type NotificationConfiguration struct { - CloudFunctionConfiguration *CloudFunctionConfiguration `type:"structure"` - - QueueConfiguration *QueueConfiguration `type:"structure"` - - TopicConfiguration *TopicConfiguration `type:"structure"` - - metadataNotificationConfiguration `json:"-", xml:"-"` -} - -type metadataNotificationConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type Object struct { - ETag *string `type:"string"` - - Key *string `type:"string"` - - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - Size *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - metadataObject `json:"-", xml:"-"` -} - -type metadataObject struct { - SDKShapeTraits bool `type:"structure"` -} - -type ObjectIdentifier struct { - // Key name of the object to delete. - Key *string `type:"string" required:"true"` - - // VersionId for the specific version of the object to delete. - VersionID *string `locationName:"VersionId" type:"string"` - - metadataObjectIdentifier `json:"-", xml:"-"` -} - -type metadataObjectIdentifier struct { - SDKShapeTraits bool `type:"structure"` -} - -type ObjectVersion struct { - ETag *string `type:"string"` - - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - // Size in bytes of the object. - Size *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - // Version ID of an object. - VersionID *string `locationName:"VersionId" type:"string"` - - metadataObjectVersion `json:"-", xml:"-"` -} - -type metadataObjectVersion struct { - SDKShapeTraits bool `type:"structure"` -} - -type Owner struct { - DisplayName *string `type:"string"` - - ID *string `type:"string"` - - metadataOwner `json:"-", xml:"-"` -} - -type metadataOwner struct { - SDKShapeTraits bool `type:"structure"` -} - -type Part struct { - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` - - // Date and time at which the part was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Part number identifying the part. - PartNumber *int64 `type:"integer"` - - // Size of the uploaded part data. - Size *int64 `type:"integer"` - - metadataPart `json:"-", xml:"-"` -} - -type metadataPart struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketACLInput struct { - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - metadataPutBucketACLInput `json:"-", xml:"-"` -} - -type metadataPutBucketACLInput struct { - SDKShapeTraits bool `type:"structure" payload:"AccessControlPolicy"` -} - -type PutBucketACLOutput struct { - metadataPutBucketACLOutput `json:"-", xml:"-"` -} - -type metadataPutBucketACLOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketCORSInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure"` - - metadataPutBucketCORSInput `json:"-", xml:"-"` -} - -type metadataPutBucketCORSInput struct { - SDKShapeTraits bool `type:"structure" payload:"CORSConfiguration"` -} - -type PutBucketCORSOutput struct { - metadataPutBucketCORSOutput `json:"-", xml:"-"` -} - -type metadataPutBucketCORSOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketLifecycleInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - LifecycleConfiguration *LifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure"` - - metadataPutBucketLifecycleInput `json:"-", xml:"-"` -} - -type metadataPutBucketLifecycleInput struct { - SDKShapeTraits bool `type:"structure" payload:"LifecycleConfiguration"` -} - -type PutBucketLifecycleOutput struct { - metadataPutBucketLifecycleOutput `json:"-", xml:"-"` -} - -type metadataPutBucketLifecycleOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketLoggingInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - BucketLoggingStatus *BucketLoggingStatus `locationName:"BucketLoggingStatus" type:"structure" required:"true"` - - metadataPutBucketLoggingInput `json:"-", xml:"-"` -} - -type metadataPutBucketLoggingInput struct { - SDKShapeTraits bool `type:"structure" payload:"BucketLoggingStatus"` -} - -type PutBucketLoggingOutput struct { - metadataPutBucketLoggingOutput `json:"-", xml:"-"` -} - -type metadataPutBucketLoggingOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketNotificationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - NotificationConfiguration *NotificationConfiguration `locationName:"NotificationConfiguration" type:"structure" required:"true"` - - metadataPutBucketNotificationInput `json:"-", xml:"-"` -} - -type metadataPutBucketNotificationInput struct { - SDKShapeTraits bool `type:"structure" payload:"NotificationConfiguration"` -} - -type PutBucketNotificationOutput struct { - metadataPutBucketNotificationOutput `json:"-", xml:"-"` -} - -type metadataPutBucketNotificationOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketPolicyInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The bucket policy as a JSON document. - Policy *string `type:"string" required:"true"` - - metadataPutBucketPolicyInput `json:"-", xml:"-"` -} - -type metadataPutBucketPolicyInput struct { - SDKShapeTraits bool `type:"structure" payload:"Policy"` -} - -type PutBucketPolicyOutput struct { - metadataPutBucketPolicyOutput `json:"-", xml:"-"` -} - -type metadataPutBucketPolicyOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketReplicationInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - ReplicationConfiguration *ReplicationConfiguration `locationName:"ReplicationConfiguration" type:"structure" required:"true"` - - metadataPutBucketReplicationInput `json:"-", xml:"-"` -} - -type metadataPutBucketReplicationInput struct { - SDKShapeTraits bool `type:"structure" payload:"ReplicationConfiguration"` -} - -type PutBucketReplicationOutput struct { - metadataPutBucketReplicationOutput `json:"-", xml:"-"` -} - -type metadataPutBucketReplicationOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketRequestPaymentInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - RequestPaymentConfiguration *RequestPaymentConfiguration `locationName:"RequestPaymentConfiguration" type:"structure" required:"true"` - - metadataPutBucketRequestPaymentInput `json:"-", xml:"-"` -} - -type metadataPutBucketRequestPaymentInput struct { - SDKShapeTraits bool `type:"structure" payload:"RequestPaymentConfiguration"` -} - -type PutBucketRequestPaymentOutput struct { - metadataPutBucketRequestPaymentOutput `json:"-", xml:"-"` -} - -type metadataPutBucketRequestPaymentOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketTaggingInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true"` - - metadataPutBucketTaggingInput `json:"-", xml:"-"` -} - -type metadataPutBucketTaggingInput struct { - SDKShapeTraits bool `type:"structure" payload:"Tagging"` -} - -type PutBucketTaggingOutput struct { - metadataPutBucketTaggingOutput `json:"-", xml:"-"` -} - -type metadataPutBucketTaggingOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketVersioningInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - VersioningConfiguration *VersioningConfiguration `locationName:"VersioningConfiguration" type:"structure" required:"true"` - - metadataPutBucketVersioningInput `json:"-", xml:"-"` -} - -type metadataPutBucketVersioningInput struct { - SDKShapeTraits bool `type:"structure" payload:"VersioningConfiguration"` -} - -type PutBucketVersioningOutput struct { - metadataPutBucketVersioningOutput `json:"-", xml:"-"` -} - -type metadataPutBucketVersioningOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutBucketWebsiteInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - WebsiteConfiguration *WebsiteConfiguration `locationName:"WebsiteConfiguration" type:"structure" required:"true"` - - metadataPutBucketWebsiteInput `json:"-", xml:"-"` -} - -type metadataPutBucketWebsiteInput struct { - SDKShapeTraits bool `type:"structure" payload:"WebsiteConfiguration"` -} - -type PutBucketWebsiteOutput struct { - metadataPutBucketWebsiteOutput `json:"-", xml:"-"` -} - -type metadataPutBucketWebsiteOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutObjectACLInput struct { - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - metadataPutObjectACLInput `json:"-", xml:"-"` -} - -type metadataPutObjectACLInput struct { - SDKShapeTraits bool `type:"structure" payload:"AccessControlPolicy"` -} - -type PutObjectACLOutput struct { - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataPutObjectACLOutput `json:"-", xml:"-"` -} - -type metadataPutObjectACLOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type PutObjectInput struct { - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string"` - - // Object data. - Body io.ReadSeeker `type:"blob"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. This parameter is useful when the size of the - // body cannot be determined automatically. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"integer"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata *map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` - - metadataPutObjectInput `json:"-", xml:"-"` -} - -type metadataPutObjectInput struct { - SDKShapeTraits bool `type:"structure" payload:"Body"` -} - -type PutObjectOutput struct { - // Entity tag for the uploaded object. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - // Version of the object. - VersionID *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - metadataPutObjectOutput `json:"-", xml:"-"` -} - -type metadataPutObjectOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type QueueConfiguration struct { - Event *string `type:"string"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - ID *string `locationName:"Id" type:"string"` - - Queue *string `type:"string"` - - metadataQueueConfiguration `json:"-", xml:"-"` -} - -type metadataQueueConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type Redirect struct { - // The HTTP redirect code to use on the response. Not required if one of the - // siblings is present. - HTTPRedirectCode *string `locationName:"HttpRedirectCode" type:"string"` - - // The host name to use in the redirect request. - HostName *string `type:"string"` - - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string"` - - // The object key prefix to use in the redirect request. For example, to redirect - // requests for all pages with prefix docs/ (objects in the docs/ folder) to - // documents/, you can set a condition block with KeyPrefixEquals set to docs/ - // and in the Redirect set ReplaceKeyPrefixWith to /documents. Not required - // if one of the siblings is present. Can be present only if ReplaceKeyWith - // is not provided. - ReplaceKeyPrefixWith *string `type:"string"` - - // The specific object key to use in the redirect request. For example, redirect - // request to error.html. Not required if one of the sibling is present. Can - // be present only if ReplaceKeyPrefixWith is not provided. - ReplaceKeyWith *string `type:"string"` - - metadataRedirect `json:"-", xml:"-"` -} - -type metadataRedirect struct { - SDKShapeTraits bool `type:"structure"` -} - -type RedirectAllRequestsTo struct { - // Name of the host where requests will be redirected. - HostName *string `type:"string" required:"true"` - - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string"` - - metadataRedirectAllRequestsTo `json:"-", xml:"-"` -} - -type metadataRedirectAllRequestsTo struct { - SDKShapeTraits bool `type:"structure"` -} - -// Container for replication rules. You can add as many as 1,000 rules. Total -// replication configuration size can be up to 2 MB. -type ReplicationConfiguration struct { - // Amazon Resource Name (ARN) of an IAM role for Amazon S3 to assume when replicating - // the objects. - Role *string `type:"string" required:"true"` - - // Container for information about a particular replication rule. Replication - // configuration must have at least one rule and can contain up to 1,000 rules. - Rules []*ReplicationRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` - - metadataReplicationConfiguration `json:"-", xml:"-"` -} - -type metadataReplicationConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type ReplicationRule struct { - Destination *Destination `type:"structure" required:"true"` - - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` - - // Object keyname prefix identifying one or more objects to which the rule applies. - // Maximum prefix length can be up to 1,024 characters. Overlapping prefixes - // are not supported. - Prefix *string `type:"string" required:"true"` - - // The rule is ignored if status is not Enabled. - Status *string `type:"string" required:"true"` - - metadataReplicationRule `json:"-", xml:"-"` -} - -type metadataReplicationRule struct { - SDKShapeTraits bool `type:"structure"` -} - -type RequestPaymentConfiguration struct { - // Specifies who pays for the download and request fees. - Payer *string `type:"string" required:"true"` - - metadataRequestPaymentConfiguration `json:"-", xml:"-"` -} - -type metadataRequestPaymentConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type RestoreObjectInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - RestoreRequest *RestoreRequest `locationName:"RestoreRequest" type:"structure"` - - VersionID *string `location:"querystring" locationName:"versionId" type:"string"` - - metadataRestoreObjectInput `json:"-", xml:"-"` -} - -type metadataRestoreObjectInput struct { - SDKShapeTraits bool `type:"structure" payload:"RestoreRequest"` -} - -type RestoreObjectOutput struct { - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - metadataRestoreObjectOutput `json:"-", xml:"-"` -} - -type metadataRestoreObjectOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type RestoreRequest struct { - // Lifetime of the active copy in days - Days *int64 `type:"integer" required:"true"` - - metadataRestoreRequest `json:"-", xml:"-"` -} - -type metadataRestoreRequest struct { - SDKShapeTraits bool `type:"structure"` -} - -type RoutingRule struct { - // A container for describing a condition that must be met for the specified - // redirect to apply. For example, 1. If request is for pages in the /docs folder, - // redirect to the /documents folder. 2. If request results in HTTP error 4xx, - // redirect request to another host where you might process the error. - Condition *Condition `type:"structure"` - - // Container for redirect information. You can redirect requests to another - // host, to another page, or with another protocol. In the event of an error, - // you can can specify a different error code to return. - Redirect *Redirect `type:"structure" required:"true"` - - metadataRoutingRule `json:"-", xml:"-"` -} - -type metadataRoutingRule struct { - SDKShapeTraits bool `type:"structure"` -} - -type Tag struct { - // Name of the tag. - Key *string `type:"string" required:"true"` - - // Value of the tag. - Value *string `type:"string" required:"true"` - - metadataTag `json:"-", xml:"-"` -} - -type metadataTag struct { - SDKShapeTraits bool `type:"structure"` -} - -type Tagging struct { - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` - - metadataTagging `json:"-", xml:"-"` -} - -type metadataTagging struct { - SDKShapeTraits bool `type:"structure"` -} - -type TargetGrant struct { - Grantee *Grantee `type:"structure"` - - // Logging permissions assigned to the Grantee for the bucket. - Permission *string `type:"string"` - - metadataTargetGrant `json:"-", xml:"-"` -} - -type metadataTargetGrant struct { - SDKShapeTraits bool `type:"structure"` -} - -type TopicConfiguration struct { - // Bucket event for which to send notifications. - Event *string `type:"string"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - ID *string `locationName:"Id" type:"string"` - - // Amazon SNS topic to which Amazon S3 will publish a message to report the - // specified events for the bucket. - Topic *string `type:"string"` - - metadataTopicConfiguration `json:"-", xml:"-"` -} - -type metadataTopicConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type Transition struct { - // Indicates at what date the object is to be moved or deleted. Should be in - // GMT ISO 8601 Format. - Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Indicates the lifetime, in days, of the objects that are subject to the rule. - // The value must be a non-zero positive integer. - Days *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string"` - - metadataTransition `json:"-", xml:"-"` -} - -type metadataTransition struct { - SDKShapeTraits bool `type:"structure"` -} - -type UploadPartCopyInput struct { - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. - CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` - - // Copies the object if its entity tag (ETag) matches the specified tag. - CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` - - // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Copies the object if its entity tag (ETag) is different than the specified - // ETag. - CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` - - // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` - - // The range of bytes to copy from the source object. The range value must use - // the form bytes=first-last, where the first and last are the zero-based byte - // offsets to copy. For example, bytes=0-9 indicates that you want to copy the - // first ten bytes of the source. You can copy a range only if the source object - // is greater than 5 GB. - CopySourceRange *string `location:"header" locationName:"x-amz-copy-source-range" type:"string"` - - // Specifies the algorithm to use when decrypting the source object (e.g., AES256). - CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt - // the source object. The encryption key provided in this header must be one - // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Part number of part being copied. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. This must be the same encryption key specified in the initiate multipart - // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Upload ID identifying the multipart upload whose part is being copied. - UploadID *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` - - metadataUploadPartCopyInput `json:"-", xml:"-"` -} - -type metadataUploadPartCopyInput struct { - SDKShapeTraits bool `type:"structure"` -} - -type UploadPartCopyOutput struct { - CopyPartResult *CopyPartResult `type:"structure"` - - // The version of the source object that was copied, if you have enabled versioning - // on the source bucket. - CopySourceVersionID *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - metadataUploadPartCopyOutput `json:"-", xml:"-"` -} - -type metadataUploadPartCopyOutput struct { - SDKShapeTraits bool `type:"structure" payload:"CopyPartResult"` -} - -type UploadPartInput struct { - Body io.ReadSeeker `type:"blob"` - - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Size of the body in bytes. This parameter is useful when the size of the - // body cannot be determined automatically. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"integer"` - - Key *string `location:"uri" locationName:"Key" type:"string" required:"true"` - - // Part number of part being uploaded. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256, - // aws:kms). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. This must be the same encryption key specified in the initiate multipart - // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Upload ID identifying the multipart upload whose part is being uploaded. - UploadID *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` - - metadataUploadPartInput `json:"-", xml:"-"` -} - -type metadataUploadPartInput struct { - SDKShapeTraits bool `type:"structure" payload:"Body"` -} - -type UploadPartOutput struct { - // Entity tag for the uploaded object. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyID *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string"` - - metadataUploadPartOutput `json:"-", xml:"-"` -} - -type metadataUploadPartOutput struct { - SDKShapeTraits bool `type:"structure"` -} - -type VersioningConfiguration struct { - // Specifies whether MFA delete is enabled in the bucket versioning configuration. - // This element is only returned if the bucket has been configured with MFA - // delete. If the bucket has never been so configured, this element is not returned. - MFADelete *string `locationName:"MfaDelete" type:"string"` - - // The versioning state of the bucket. - Status *string `type:"string"` - - metadataVersioningConfiguration `json:"-", xml:"-"` -} - -type metadataVersioningConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} - -type WebsiteConfiguration struct { - ErrorDocument *ErrorDocument `type:"structure"` - - IndexDocument *IndexDocument `type:"structure"` - - RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - - RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` - - metadataWebsiteConfiguration `json:"-", xml:"-"` -} - -type metadataWebsiteConfiguration struct { - SDKShapeTraits bool `type:"structure"` -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location.go deleted file mode 100644 index cbed183d..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location.go +++ /dev/null @@ -1,41 +0,0 @@ -package s3 - -import ( - "io/ioutil" - "regexp" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/aws/awsutil" -) - -var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`) - -func buildGetBucketLocation(r *aws.Request) { - if r.DataFilled() { - out := r.Data.(*GetBucketLocationOutput) - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = err - return - } - - match := reBucketLocation.FindSubmatch(b) - if len(match) > 1 { - loc := string(match[1]) - out.LocationConstraint = &loc - } - } -} - -func populateLocationConstraint(r *aws.Request) { - if r.ParamsFilled() && 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, - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location_test.go deleted file mode 100644 index e5932e0b..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/bucket_location_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package s3_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/aws/awsutil" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var s3LocationTests = []struct { - body string - loc string -}{ - {``, ``}, - {`EU`, `EU`}, -} - -func TestGetBucketLocation(t *testing.T) { - for _, test := range s3LocationTests { - s := s3.New(baseConfig) - s.Handlers.Send.Clear() - s.Handlers.Send.PushBack(func(r *aws.Request) { - reader := ioutil.NopCloser(bytes.NewReader([]byte(test.body))) - r.HTTPResponse = &http.Response{StatusCode: 200, Body: reader} - }) - - resp, err := s.GetBucketLocation(&s3.GetBucketLocationInput{Bucket: aws.String("bucket")}) - assert.NoError(t, err) - if test.loc == "" { - assert.Nil(t, resp.LocationConstraint) - } else { - assert.Equal(t, test.loc, *resp.LocationConstraint) - } - } -} - -func TestPopulateLocationConstraint(t *testing.T) { - s := s3.New(baseConfig) - in := &s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - } - req, _ := s.CreateBucketRequest(in) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, "mock-region", awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint")[0]) - assert.Nil(t, in.CreateBucketConfiguration) // don't modify original params -} - -func TestNoPopulateLocationConstraintIfProvided(t *testing.T) { - s := s3.New(baseConfig) - req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - CreateBucketConfiguration: &s3.CreateBucketConfiguration{}, - }) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint"))) -} - -func TestNoPopulateLocationConstraintIfClassic(t *testing.T) { - s := s3.New(baseConfig.Merge(&aws.Config{Region: "us-east-1"})) - req, _ := s.CreateBucketRequest(&s3.CreateBucketInput{ - Bucket: aws.String("bucket"), - }) - err := req.Build() - assert.NoError(t, err) - assert.Equal(t, 0, len(awsutil.ValuesAtPath(req.Params, "CreateBucketConfiguration.LocationConstraint"))) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/content_md5.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/content_md5.go deleted file mode 100644 index bb47ff61..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/content_md5.go +++ /dev/null @@ -1,36 +0,0 @@ -package s3 - -import ( - "crypto/md5" - "encoding/base64" - "fmt" - "io" - - "github.com/awslabs/aws-sdk-go/aws" -) - -// contentMD5 computes and sets the HTTP Content-MD5 header for requests that -// require it. -func contentMD5(r *aws.Request) { - h := md5.New() - - // hash the body. seek back to the first position after reading to reset - // the body for transmission. copy errors may be assumed to be from the - // body. - _, err := io.Copy(h, r.Body) - if err != nil { - r.Error = fmt.Errorf("content-md5: read: %v", err) - return - } - _, err = r.Body.Seek(0, 0) - if err != nil { - r.Error = fmt.Errorf("content-md5: seek: %v", err) - return - } - - // encode the md5 checksum in base64 and set the request header. - sum := h.Sum(nil) - sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum))) - base64.StdEncoding.Encode(sum64, sum) - r.HTTPRequest.Header.Set("Content-MD5", string(sum64)) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations.go deleted file mode 100644 index b23c207d..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations.go +++ /dev/null @@ -1,32 +0,0 @@ -package s3 - -import "github.com/awslabs/aws-sdk-go/aws" - -func init() { - initService = func(s *aws.Service) { - // Support building custom host-style bucket endpoints - s.Handlers.Build.PushFront(updateHostWithBucket) - - // Require SSL when using SSE keys - s.Handlers.Validate.PushBack(validateSSERequiresSSL) - s.Handlers.Build.PushBack(computeSSEKeys) - - // S3 uses custom error unmarshaling logic - s.Handlers.UnmarshalError.Clear() - s.Handlers.UnmarshalError.PushBack(unmarshalError) - } - - initRequest = func(r *aws.Request) { - switch r.Operation { - case opPutBucketCORS, opPutBucketLifecycle, opPutBucketTagging, opDeleteObjects: - // These S3 operations require Content-MD5 to be set - r.Handlers.Build.PushBack(contentMD5) - case opGetBucketLocation: - // GetBucketLocation has custom parsing logic - r.Handlers.Unmarshal.PushFront(buildGetBucketLocation) - case opCreateBucket: - // Auto-populate LocationConstraint with current region - r.Handlers.Validate.PushFront(populateLocationConstraint) - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations_test.go deleted file mode 100644 index f9675870..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/customizations_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package s3_test - -import ( - "crypto/md5" - "encoding/base64" - "io/ioutil" - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -func assertMD5(t *testing.T, req *aws.Request) { - err := req.Build() - assert.NoError(t, err) - - b, _ := ioutil.ReadAll(req.HTTPRequest.Body) - out := md5.Sum(b) - assert.NotEmpty(t, b) - assert.Equal(t, base64.StdEncoding.EncodeToString(out[:]), req.HTTPRequest.Header.Get("Content-MD5")) -} - -func TestMD5InPutBucketCORS(t *testing.T) { - svc := s3.New(baseConfig) - req, _ := svc.PutBucketCORSRequest(&s3.PutBucketCORSInput{ - Bucket: aws.String("bucketname"), - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{ - {AllowedMethods: []*string{aws.String("GET")}}, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InPutBucketLifecycle(t *testing.T) { - svc := s3.New(baseConfig) - req, _ := svc.PutBucketLifecycleRequest(&s3.PutBucketLifecycleInput{ - Bucket: aws.String("bucketname"), - LifecycleConfiguration: &s3.LifecycleConfiguration{ - Rules: []*s3.LifecycleRule{ - { - ID: aws.String("ID"), - Prefix: aws.String("Prefix"), - Status: aws.String("Enabled"), - }, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InPutBucketTagging(t *testing.T) { - svc := s3.New(baseConfig) - req, _ := svc.PutBucketTaggingRequest(&s3.PutBucketTaggingInput{ - Bucket: aws.String("bucketname"), - Tagging: &s3.Tagging{ - TagSet: []*s3.Tag{ - {Key: aws.String("KEY"), Value: aws.String("VALUE")}, - }, - }, - }) - assertMD5(t, req) -} - -func TestMD5InDeleteObjects(t *testing.T) { - svc := s3.New(baseConfig) - req, _ := svc.DeleteObjectsRequest(&s3.DeleteObjectsInput{ - Bucket: aws.String("bucketname"), - Delete: &s3.Delete{ - Objects: []*s3.ObjectIdentifier{ - {Key: aws.String("key")}, - }, - }, - }) - assertMD5(t, req) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/examples_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/examples_test.go deleted file mode 100644 index 3471b6b2..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/examples_test.go +++ /dev/null @@ -1,1472 +0,0 @@ -package s3_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/aws/awsutil" - "github.com/awslabs/aws-sdk-go/service/s3" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleS3_AbortMultipartUpload() { - svc := s3.New(nil) - - params := &s3.AbortMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadID: aws.String("MultipartUploadId"), // Required - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.AbortMultipartUpload(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_CompleteMultipartUpload() { - svc := s3.New(nil) - - params := &s3.CompleteMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadID: aws.String("MultipartUploadId"), // Required - MultipartUpload: &s3.CompletedMultipartUpload{ - Parts: []*s3.CompletedPart{ - { // Required - ETag: aws.String("ETag"), - PartNumber: aws.Long(1), - }, - // More values... - }, - }, - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.CompleteMultipartUpload(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_CopyObject() { - svc := s3.New(nil) - - params := &s3.CopyObjectInput{ - Bucket: aws.String("BucketName"), // Required - CopySource: aws.String("CopySource"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentType: aws.String("ContentType"), - CopySourceIfMatch: aws.String("CopySourceIfMatch"), - CopySourceIfModifiedSince: aws.Time(time.Now()), - CopySourceIfNoneMatch: aws.String("CopySourceIfNoneMatch"), - CopySourceIfUnmodifiedSince: aws.Time(time.Now()), - CopySourceSSECustomerAlgorithm: aws.String("CopySourceSSECustomerAlgorithm"), - CopySourceSSECustomerKey: aws.String("CopySourceSSECustomerKey"), - CopySourceSSECustomerKeyMD5: aws.String("CopySourceSSECustomerKeyMD5"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: &map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - MetadataDirective: aws.String("MetadataDirective"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyID: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.CopyObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_CreateBucket() { - svc := s3.New(nil) - - params := &s3.CreateBucketInput{ - Bucket: aws.String("BucketName"), // Required - ACL: aws.String("BucketCannedACL"), - CreateBucketConfiguration: &s3.CreateBucketConfiguration{ - LocationConstraint: aws.String("BucketLocationConstraint"), - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - } - resp, err := svc.CreateBucket(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_CreateMultipartUpload() { - svc := s3.New(nil) - - params := &s3.CreateMultipartUploadInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentType: aws.String("ContentType"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: &map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyID: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.CreateMultipartUpload(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucket() { - svc := s3.New(nil) - - params := &s3.DeleteBucketInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucket(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketCORS() { - svc := s3.New(nil) - - params := &s3.DeleteBucketCORSInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketCORS(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.DeleteBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketLifecycle(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketPolicy() { - svc := s3.New(nil) - - params := &s3.DeleteBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketPolicy(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketReplication() { - svc := s3.New(nil) - - params := &s3.DeleteBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketReplication(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketTagging() { - svc := s3.New(nil) - - params := &s3.DeleteBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketTagging(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteBucketWebsite() { - svc := s3.New(nil) - - params := &s3.DeleteBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.DeleteBucketWebsite(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteObject() { - svc := s3.New(nil) - - params := &s3.DeleteObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - MFA: aws.String("MFA"), - RequestPayer: aws.String("RequestPayer"), - VersionID: aws.String("ObjectVersionId"), - } - resp, err := svc.DeleteObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_DeleteObjects() { - svc := s3.New(nil) - - params := &s3.DeleteObjectsInput{ - Bucket: aws.String("BucketName"), // Required - Delete: &s3.Delete{ // Required - Objects: []*s3.ObjectIdentifier{ // Required - { // Required - Key: aws.String("ObjectKey"), // Required - VersionID: aws.String("ObjectVersionId"), - }, - // More values... - }, - Quiet: aws.Boolean(true), - }, - MFA: aws.String("MFA"), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.DeleteObjects(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketACL() { - svc := s3.New(nil) - - params := &s3.GetBucketACLInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketACL(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketCORS() { - svc := s3.New(nil) - - params := &s3.GetBucketCORSInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketCORS(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.GetBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLifecycle(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketLocation() { - svc := s3.New(nil) - - params := &s3.GetBucketLocationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLocation(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketLogging() { - svc := s3.New(nil) - - params := &s3.GetBucketLoggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketLogging(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketNotification() { - svc := s3.New(nil) - - params := &s3.GetBucketNotificationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketNotification(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketPolicy() { - svc := s3.New(nil) - - params := &s3.GetBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketPolicy(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketReplication() { - svc := s3.New(nil) - - params := &s3.GetBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketReplication(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketRequestPayment() { - svc := s3.New(nil) - - params := &s3.GetBucketRequestPaymentInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketRequestPayment(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketTagging() { - svc := s3.New(nil) - - params := &s3.GetBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketTagging(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketVersioning() { - svc := s3.New(nil) - - params := &s3.GetBucketVersioningInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketVersioning(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetBucketWebsite() { - svc := s3.New(nil) - - params := &s3.GetBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.GetBucketWebsite(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetObject() { - svc := s3.New(nil) - - params := &s3.GetObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - IfMatch: aws.String("IfMatch"), - IfModifiedSince: aws.Time(time.Now()), - IfNoneMatch: aws.String("IfNoneMatch"), - IfUnmodifiedSince: aws.Time(time.Now()), - Range: aws.String("Range"), - RequestPayer: aws.String("RequestPayer"), - ResponseCacheControl: aws.String("ResponseCacheControl"), - ResponseContentDisposition: aws.String("ResponseContentDisposition"), - ResponseContentEncoding: aws.String("ResponseContentEncoding"), - ResponseContentLanguage: aws.String("ResponseContentLanguage"), - ResponseContentType: aws.String("ResponseContentType"), - ResponseExpires: aws.Time(time.Now()), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - VersionID: aws.String("ObjectVersionId"), - } - resp, err := svc.GetObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetObjectACL() { - svc := s3.New(nil) - - params := &s3.GetObjectACLInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - VersionID: aws.String("ObjectVersionId"), - } - resp, err := svc.GetObjectACL(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_GetObjectTorrent() { - svc := s3.New(nil) - - params := &s3.GetObjectTorrentInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.GetObjectTorrent(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_HeadBucket() { - svc := s3.New(nil) - - params := &s3.HeadBucketInput{ - Bucket: aws.String("BucketName"), // Required - } - resp, err := svc.HeadBucket(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_HeadObject() { - svc := s3.New(nil) - - params := &s3.HeadObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - IfMatch: aws.String("IfMatch"), - IfModifiedSince: aws.Time(time.Now()), - IfNoneMatch: aws.String("IfNoneMatch"), - IfUnmodifiedSince: aws.Time(time.Now()), - Range: aws.String("Range"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - VersionID: aws.String("ObjectVersionId"), - } - resp, err := svc.HeadObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_ListBuckets() { - svc := s3.New(nil) - - var params *s3.ListBucketsInput - resp, err := svc.ListBuckets(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_ListMultipartUploads() { - svc := s3.New(nil) - - params := &s3.ListMultipartUploadsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - KeyMarker: aws.String("KeyMarker"), - MaxUploads: aws.Long(1), - Prefix: aws.String("Prefix"), - UploadIDMarker: aws.String("UploadIdMarker"), - } - resp, err := svc.ListMultipartUploads(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_ListObjectVersions() { - svc := s3.New(nil) - - params := &s3.ListObjectVersionsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - KeyMarker: aws.String("KeyMarker"), - MaxKeys: aws.Long(1), - Prefix: aws.String("Prefix"), - VersionIDMarker: aws.String("VersionIdMarker"), - } - resp, err := svc.ListObjectVersions(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_ListObjects() { - svc := s3.New(nil) - - params := &s3.ListObjectsInput{ - Bucket: aws.String("BucketName"), // Required - Delimiter: aws.String("Delimiter"), - EncodingType: aws.String("EncodingType"), - Marker: aws.String("Marker"), - MaxKeys: aws.Long(1), - Prefix: aws.String("Prefix"), - } - resp, err := svc.ListObjects(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_ListParts() { - svc := s3.New(nil) - - params := &s3.ListPartsInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - UploadID: aws.String("MultipartUploadId"), // Required - MaxParts: aws.Long(1), - PartNumberMarker: aws.Long(1), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.ListParts(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketACL() { - svc := s3.New(nil) - - params := &s3.PutBucketACLInput{ - Bucket: aws.String("BucketName"), // Required - ACL: aws.String("BucketCannedACL"), - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: []*s3.Grant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("Permission"), - }, - // More values... - }, - Owner: &s3.Owner{ - DisplayName: aws.String("DisplayName"), - ID: aws.String("ID"), - }, - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - } - resp, err := svc.PutBucketACL(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketCORS() { - svc := s3.New(nil) - - params := &s3.PutBucketCORSInput{ - Bucket: aws.String("BucketName"), // Required - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{ - { // Required - AllowedHeaders: []*string{ - aws.String("AllowedHeader"), // Required - // More values... - }, - AllowedMethods: []*string{ - aws.String("AllowedMethod"), // Required - // More values... - }, - AllowedOrigins: []*string{ - aws.String("AllowedOrigin"), // Required - // More values... - }, - ExposeHeaders: []*string{ - aws.String("ExposeHeader"), // Required - // More values... - }, - MaxAgeSeconds: aws.Long(1), - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketCORS(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketLifecycle() { - svc := s3.New(nil) - - params := &s3.PutBucketLifecycleInput{ - Bucket: aws.String("BucketName"), // Required - LifecycleConfiguration: &s3.LifecycleConfiguration{ - Rules: []*s3.LifecycleRule{ // Required - { // Required - Prefix: aws.String("Prefix"), // Required - Status: aws.String("ExpirationStatus"), // Required - Expiration: &s3.LifecycleExpiration{ - Date: aws.Time(time.Now()), - Days: aws.Long(1), - }, - ID: aws.String("ID"), - NoncurrentVersionExpiration: &s3.NoncurrentVersionExpiration{ - NoncurrentDays: aws.Long(1), - }, - NoncurrentVersionTransition: &s3.NoncurrentVersionTransition{ - NoncurrentDays: aws.Long(1), - StorageClass: aws.String("TransitionStorageClass"), - }, - Transition: &s3.Transition{ - Date: aws.Time(time.Now()), - Days: aws.Long(1), - StorageClass: aws.String("TransitionStorageClass"), - }, - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketLifecycle(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketLogging() { - svc := s3.New(nil) - - params := &s3.PutBucketLoggingInput{ - Bucket: aws.String("BucketName"), // Required - BucketLoggingStatus: &s3.BucketLoggingStatus{ // Required - LoggingEnabled: &s3.LoggingEnabled{ - TargetBucket: aws.String("TargetBucket"), - TargetGrants: []*s3.TargetGrant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("BucketLogsPermission"), - }, - // More values... - }, - TargetPrefix: aws.String("TargetPrefix"), - }, - }, - } - resp, err := svc.PutBucketLogging(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketNotification() { - svc := s3.New(nil) - - params := &s3.PutBucketNotificationInput{ - Bucket: aws.String("BucketName"), // Required - NotificationConfiguration: &s3.NotificationConfiguration{ // Required - CloudFunctionConfiguration: &s3.CloudFunctionConfiguration{ - CloudFunction: aws.String("CloudFunction"), - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - ID: aws.String("NotificationId"), - InvocationRole: aws.String("CloudFunctionInvocationRole"), - }, - QueueConfiguration: &s3.QueueConfiguration{ - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - ID: aws.String("NotificationId"), - Queue: aws.String("Queue"), - }, - TopicConfiguration: &s3.TopicConfiguration{ - Event: aws.String("Event"), - Events: []*string{ - aws.String("Event"), // Required - // More values... - }, - ID: aws.String("NotificationId"), - Topic: aws.String("Topic"), - }, - }, - } - resp, err := svc.PutBucketNotification(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketPolicy() { - svc := s3.New(nil) - - params := &s3.PutBucketPolicyInput{ - Bucket: aws.String("BucketName"), // Required - Policy: aws.String("Policy"), // Required - } - resp, err := svc.PutBucketPolicy(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketReplication() { - svc := s3.New(nil) - - params := &s3.PutBucketReplicationInput{ - Bucket: aws.String("BucketName"), // Required - ReplicationConfiguration: &s3.ReplicationConfiguration{ // Required - Role: aws.String("Role"), // Required - Rules: []*s3.ReplicationRule{ // Required - { // Required - Destination: &s3.Destination{ // Required - Bucket: aws.String("BucketName"), // Required - }, - Prefix: aws.String("Prefix"), // Required - Status: aws.String("ReplicationRuleStatus"), // Required - ID: aws.String("ID"), - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketReplication(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketRequestPayment() { - svc := s3.New(nil) - - params := &s3.PutBucketRequestPaymentInput{ - Bucket: aws.String("BucketName"), // Required - RequestPaymentConfiguration: &s3.RequestPaymentConfiguration{ // Required - Payer: aws.String("Payer"), // Required - }, - } - resp, err := svc.PutBucketRequestPayment(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketTagging() { - svc := s3.New(nil) - - params := &s3.PutBucketTaggingInput{ - Bucket: aws.String("BucketName"), // Required - Tagging: &s3.Tagging{ // Required - TagSet: []*s3.Tag{ // Required - { // Required - Key: aws.String("ObjectKey"), // Required - Value: aws.String("Value"), // Required - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketTagging(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketVersioning() { - svc := s3.New(nil) - - params := &s3.PutBucketVersioningInput{ - Bucket: aws.String("BucketName"), // Required - VersioningConfiguration: &s3.VersioningConfiguration{ // Required - MFADelete: aws.String("MFADelete"), - Status: aws.String("BucketVersioningStatus"), - }, - MFA: aws.String("MFA"), - } - resp, err := svc.PutBucketVersioning(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutBucketWebsite() { - svc := s3.New(nil) - - params := &s3.PutBucketWebsiteInput{ - Bucket: aws.String("BucketName"), // Required - WebsiteConfiguration: &s3.WebsiteConfiguration{ // Required - ErrorDocument: &s3.ErrorDocument{ - Key: aws.String("ObjectKey"), // Required - }, - IndexDocument: &s3.IndexDocument{ - Suffix: aws.String("Suffix"), // Required - }, - RedirectAllRequestsTo: &s3.RedirectAllRequestsTo{ - HostName: aws.String("HostName"), // Required - Protocol: aws.String("Protocol"), - }, - RoutingRules: []*s3.RoutingRule{ - { // Required - Redirect: &s3.Redirect{ // Required - HTTPRedirectCode: aws.String("HttpRedirectCode"), - HostName: aws.String("HostName"), - Protocol: aws.String("Protocol"), - ReplaceKeyPrefixWith: aws.String("ReplaceKeyPrefixWith"), - ReplaceKeyWith: aws.String("ReplaceKeyWith"), - }, - Condition: &s3.Condition{ - HTTPErrorCodeReturnedEquals: aws.String("HttpErrorCodeReturnedEquals"), - KeyPrefixEquals: aws.String("KeyPrefixEquals"), - }, - }, - // More values... - }, - }, - } - resp, err := svc.PutBucketWebsite(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutObject() { - svc := s3.New(nil) - - params := &s3.PutObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - Body: bytes.NewReader([]byte("PAYLOAD")), - CacheControl: aws.String("CacheControl"), - ContentDisposition: aws.String("ContentDisposition"), - ContentEncoding: aws.String("ContentEncoding"), - ContentLanguage: aws.String("ContentLanguage"), - ContentLength: aws.Long(1), - ContentType: aws.String("ContentType"), - Expires: aws.Time(time.Now()), - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWriteACP: aws.String("GrantWriteACP"), - Metadata: &map[string]*string{ - "Key": aws.String("MetadataValue"), // Required - // More values... - }, - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - SSEKMSKeyID: aws.String("SSEKMSKeyId"), - ServerSideEncryption: aws.String("ServerSideEncryption"), - StorageClass: aws.String("StorageClass"), - WebsiteRedirectLocation: aws.String("WebsiteRedirectLocation"), - } - resp, err := svc.PutObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_PutObjectACL() { - svc := s3.New(nil) - - params := &s3.PutObjectACLInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - ACL: aws.String("ObjectCannedACL"), - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: []*s3.Grant{ - { // Required - Grantee: &s3.Grantee{ - Type: aws.String("Type"), // Required - DisplayName: aws.String("DisplayName"), - EmailAddress: aws.String("EmailAddress"), - ID: aws.String("ID"), - URI: aws.String("URI"), - }, - Permission: aws.String("Permission"), - }, - // More values... - }, - Owner: &s3.Owner{ - DisplayName: aws.String("DisplayName"), - ID: aws.String("ID"), - }, - }, - GrantFullControl: aws.String("GrantFullControl"), - GrantRead: aws.String("GrantRead"), - GrantReadACP: aws.String("GrantReadACP"), - GrantWrite: aws.String("GrantWrite"), - GrantWriteACP: aws.String("GrantWriteACP"), - RequestPayer: aws.String("RequestPayer"), - } - resp, err := svc.PutObjectACL(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_RestoreObject() { - svc := s3.New(nil) - - params := &s3.RestoreObjectInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - RequestPayer: aws.String("RequestPayer"), - RestoreRequest: &s3.RestoreRequest{ - Days: aws.Long(1), // Required - }, - VersionID: aws.String("ObjectVersionId"), - } - resp, err := svc.RestoreObject(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_UploadPart() { - svc := s3.New(nil) - - params := &s3.UploadPartInput{ - Bucket: aws.String("BucketName"), // Required - Key: aws.String("ObjectKey"), // Required - PartNumber: aws.Long(1), // Required - UploadID: aws.String("MultipartUploadId"), // Required - Body: bytes.NewReader([]byte("PAYLOAD")), - ContentLength: aws.Long(1), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - } - resp, err := svc.UploadPart(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} - -func ExampleS3_UploadPartCopy() { - svc := s3.New(nil) - - params := &s3.UploadPartCopyInput{ - Bucket: aws.String("BucketName"), // Required - CopySource: aws.String("CopySource"), // Required - Key: aws.String("ObjectKey"), // Required - PartNumber: aws.Long(1), // Required - UploadID: aws.String("MultipartUploadId"), // Required - CopySourceIfMatch: aws.String("CopySourceIfMatch"), - CopySourceIfModifiedSince: aws.Time(time.Now()), - CopySourceIfNoneMatch: aws.String("CopySourceIfNoneMatch"), - CopySourceIfUnmodifiedSince: aws.Time(time.Now()), - CopySourceRange: aws.String("CopySourceRange"), - CopySourceSSECustomerAlgorithm: aws.String("CopySourceSSECustomerAlgorithm"), - CopySourceSSECustomerKey: aws.String("CopySourceSSECustomerKey"), - CopySourceSSECustomerKeyMD5: aws.String("CopySourceSSECustomerKeyMD5"), - RequestPayer: aws.String("RequestPayer"), - SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"), - SSECustomerKey: aws.String("SSECustomerKey"), - SSECustomerKeyMD5: aws.String("SSECustomerKeyMD5"), - } - resp, err := svc.UploadPartCopy(params) - - if awserr := aws.Error(err); awserr != nil { - // A service error occurred. - fmt.Println("Error:", awserr.Code, awserr.Message) - } else if err != nil { - // A non-service error occurred. - panic(err) - } - - // Pretty-print the response data. - fmt.Println(awsutil.StringValue(resp)) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket.go deleted file mode 100644 index e3d6a43f..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket.go +++ /dev/null @@ -1,53 +0,0 @@ -package s3 - -import ( - "regexp" - "strings" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/aws/awsutil" -) - -var reDomain = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`) -var reIPAddress = regexp.MustCompile(`^(\d+\.){3}\d+$`) - -// dnsCompatibleBucketName returns true if the bucket name is DNS compatible. -// Buckets created outside of the classic region MUST be DNS compatible. -func dnsCompatibleBucketName(bucket string) bool { - return reDomain.MatchString(bucket) && - !reIPAddress.MatchString(bucket) && - !strings.Contains(bucket, "..") -} - -// hostStyleBucketName returns true if the request should put the bucket in -// 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 { - return false - } - - // Bucket might be DNS compatible but dots in the hostname will fail - // certificate validation, so do not use host-style. - if r.HTTPRequest.URL.Scheme == "https" && strings.Contains(bucket, ".") { - return false - } - - // Use host-style if the bucket is DNS compatible - return dnsCompatibleBucketName(bucket) -} - -func updateHostWithBucket(r *aws.Request) { - b := awsutil.ValuesAtPath(r.Params, "Bucket") - if len(b) == 0 { - return - } - - if bucket := b[0].(string); bucket != "" && hostStyleBucketName(r, bucket) { - r.HTTPRequest.URL.Host = bucket + "." + r.HTTPRequest.URL.Host - r.HTTPRequest.URL.Path = strings.Replace(r.HTTPRequest.URL.Path, "/{Bucket}", "", -1) - if r.HTTPRequest.URL.Path == "" { - r.HTTPRequest.URL.Path = "/" - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket_test.go deleted file mode 100644 index 898b47da..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/host_style_bucket_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package s3_test - -import ( - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -type s3BucketTest struct { - bucket string - url string -} - -var ( - baseConfig = &aws.Config{ - Credentials: aws.DetectCreds("AKID", "SECRET", ""), - Region: "mock-region", - } - - sslTests = []s3BucketTest{ - {"abc", "https://abc.s3.mock-region.amazonaws.com/"}, - {"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"}, - {"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"}, - {"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"}, - } - - nosslTests = []s3BucketTest{ - {"a.b.c", "http://a.b.c.s3.mock-region.amazonaws.com/"}, - {"a..bc", "http://s3.mock-region.amazonaws.com/a..bc"}, - } - - forcepathTests = []s3BucketTest{ - {"abc", "https://s3.mock-region.amazonaws.com/abc"}, - {"a$b$c", "https://s3.mock-region.amazonaws.com/a%24b%24c"}, - {"a.b.c", "https://s3.mock-region.amazonaws.com/a.b.c"}, - {"a..bc", "https://s3.mock-region.amazonaws.com/a..bc"}, - } -) - -func runTests(t *testing.T, svc *s3.S3, tests []s3BucketTest) { - for _, test := range tests { - req, _ := svc.ListObjectsRequest(&s3.ListObjectsInput{Bucket: &test.bucket}) - req.Build() - assert.Equal(t, test.url, req.HTTPRequest.URL.String()) - } -} - -func TestHostStyleBucketBuild(t *testing.T) { - s := s3.New(baseConfig) - runTests(t, s, sslTests) -} - -func TestHostStyleBucketBuildNoSSL(t *testing.T) { - s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true})) - runTests(t, s, nosslTests) -} - -func TestPathStyleBucketBuild(t *testing.T) { - s := s3.New(baseConfig.Merge(&aws.Config{S3ForcePathStyle: true})) - runTests(t, s, forcepathTests) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/integration_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/integration_test.go deleted file mode 100644 index 4a8aa341..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/integration_test.go +++ /dev/null @@ -1,107 +0,0 @@ -// +build integration - -package s3_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "os" - "testing" - "time" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var bucketName *string -var svc *s3.S3 - -func TestMain(m *testing.M) { - setup() - defer teardown() // only called if we panic - result := m.Run() - teardown() - os.Exit(result) -} - -// Create a bucket for testing -func setup() { - svc = s3.New(nil) - bucketName = aws.String( - fmt.Sprintf("aws-sdk-go-integration-%d", time.Now().Unix())) - - for i := 0; i < 10; i++ { - _, err := svc.CreateBucket(&s3.CreateBucketInput{Bucket: bucketName}) - if err == nil { - break - } - time.Sleep(1 * time.Second) - } -} - -// Delete the bucket -func teardown() { - resp, _ := svc.ListObjects(&s3.ListObjectsInput{Bucket: bucketName}) - for _, o := range resp.Contents { - svc.DeleteObject(&s3.DeleteObjectInput{Bucket: bucketName, Key: o.Key}) - } - svc.DeleteBucket(&s3.DeleteBucketInput{Bucket: bucketName}) -} - -func TestWriteToObject(t *testing.T) { - _, err := svc.PutObject(&s3.PutObjectInput{ - Bucket: bucketName, - Key: aws.String("key name"), - Body: bytes.NewReader([]byte("hello world")), - }) - assert.NoError(t, err) - - resp, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: bucketName, - Key: aws.String("key name"), - }) - assert.NoError(t, err) - - b, _ := ioutil.ReadAll(resp.Body) - assert.Equal(t, []byte("hello world"), b) -} - -func TestPresignedGetPut(t *testing.T) { - putreq, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: bucketName, - Key: aws.String("presigned-key"), - }) - - // Presign a PUT request - puturl, err := putreq.Presign(300 * time.Second) - assert.NoError(t, err) - - // PUT to the presigned URL with a body - buf := bytes.NewReader([]byte("hello world")) - puthttpreq, err := http.NewRequest("PUT", puturl, buf) - assert.NoError(t, err) - - putresp, err := http.DefaultClient.Do(puthttpreq) - assert.NoError(t, err) - assert.Equal(t, 200, putresp.StatusCode) - - // Presign a GET on the same URL - getreq, _ := svc.GetObjectRequest(&s3.GetObjectInput{ - Bucket: bucketName, - Key: aws.String("presigned-key"), - }) - - geturl, err := getreq.Presign(300 * time.Second) - assert.NoError(t, err) - - // Get the body - getresp, err := http.Get(geturl) - assert.NoError(t, err) - - defer getresp.Body.Close() - b, err := ioutil.ReadAll(getresp.Body) - assert.Equal(t, "hello world", string(b)) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/s3iface/interface.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/s3iface/interface.go deleted file mode 100644 index 0f400f18..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/s3iface/interface.go +++ /dev/null @@ -1,111 +0,0 @@ -package s3iface - -import ( - "github.com/awslabs/aws-sdk-go/service/s3" -) - -type S3API interface { - AbortMultipartUpload(*s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error) - - CompleteMultipartUpload(*s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error) - - CopyObject(*s3.CopyObjectInput) (*s3.CopyObjectOutput, error) - - CreateBucket(*s3.CreateBucketInput) (*s3.CreateBucketOutput, error) - - CreateMultipartUpload(*s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error) - - DeleteBucket(*s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error) - - DeleteBucketCORS(*s3.DeleteBucketCORSInput) (*s3.DeleteBucketCORSOutput, error) - - DeleteBucketLifecycle(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error) - - DeleteBucketPolicy(*s3.DeleteBucketPolicyInput) (*s3.DeleteBucketPolicyOutput, error) - - DeleteBucketReplication(*s3.DeleteBucketReplicationInput) (*s3.DeleteBucketReplicationOutput, error) - - DeleteBucketTagging(*s3.DeleteBucketTaggingInput) (*s3.DeleteBucketTaggingOutput, error) - - DeleteBucketWebsite(*s3.DeleteBucketWebsiteInput) (*s3.DeleteBucketWebsiteOutput, error) - - DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) - - DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error) - - GetBucketACL(*s3.GetBucketACLInput) (*s3.GetBucketACLOutput, error) - - GetBucketCORS(*s3.GetBucketCORSInput) (*s3.GetBucketCORSOutput, error) - - GetBucketLifecycle(*s3.GetBucketLifecycleInput) (*s3.GetBucketLifecycleOutput, error) - - GetBucketLocation(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) - - GetBucketLogging(*s3.GetBucketLoggingInput) (*s3.GetBucketLoggingOutput, error) - - GetBucketNotification(*s3.GetBucketNotificationInput) (*s3.GetBucketNotificationOutput, error) - - GetBucketPolicy(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) - - GetBucketReplication(*s3.GetBucketReplicationInput) (*s3.GetBucketReplicationOutput, error) - - GetBucketRequestPayment(*s3.GetBucketRequestPaymentInput) (*s3.GetBucketRequestPaymentOutput, error) - - GetBucketTagging(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) - - GetBucketVersioning(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) - - GetBucketWebsite(*s3.GetBucketWebsiteInput) (*s3.GetBucketWebsiteOutput, error) - - GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error) - - GetObjectACL(*s3.GetObjectACLInput) (*s3.GetObjectACLOutput, error) - - GetObjectTorrent(*s3.GetObjectTorrentInput) (*s3.GetObjectTorrentOutput, error) - - HeadBucket(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) - - HeadObject(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) - - ListBuckets(*s3.ListBucketsInput) (*s3.ListBucketsOutput, error) - - ListMultipartUploads(*s3.ListMultipartUploadsInput) (*s3.ListMultipartUploadsOutput, error) - - ListObjectVersions(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) - - ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error) - - ListParts(*s3.ListPartsInput) (*s3.ListPartsOutput, error) - - PutBucketACL(*s3.PutBucketACLInput) (*s3.PutBucketACLOutput, error) - - PutBucketCORS(*s3.PutBucketCORSInput) (*s3.PutBucketCORSOutput, error) - - PutBucketLifecycle(*s3.PutBucketLifecycleInput) (*s3.PutBucketLifecycleOutput, error) - - PutBucketLogging(*s3.PutBucketLoggingInput) (*s3.PutBucketLoggingOutput, error) - - PutBucketNotification(*s3.PutBucketNotificationInput) (*s3.PutBucketNotificationOutput, error) - - PutBucketPolicy(*s3.PutBucketPolicyInput) (*s3.PutBucketPolicyOutput, error) - - PutBucketReplication(*s3.PutBucketReplicationInput) (*s3.PutBucketReplicationOutput, error) - - PutBucketRequestPayment(*s3.PutBucketRequestPaymentInput) (*s3.PutBucketRequestPaymentOutput, error) - - PutBucketTagging(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) - - PutBucketVersioning(*s3.PutBucketVersioningInput) (*s3.PutBucketVersioningOutput, error) - - PutBucketWebsite(*s3.PutBucketWebsiteInput) (*s3.PutBucketWebsiteOutput, error) - - PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error) - - PutObjectACL(*s3.PutObjectACLInput) (*s3.PutObjectACLOutput, error) - - RestoreObject(*s3.RestoreObjectInput) (*s3.RestoreObjectOutput, error) - - UploadPart(*s3.UploadPartInput) (*s3.UploadPartOutput, error) - - UploadPartCopy(*s3.UploadPartCopyInput) (*s3.UploadPartCopyOutput, error) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/service.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/service.go deleted file mode 100644 index cc85d4a5..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/service.go +++ /dev/null @@ -1,59 +0,0 @@ -package s3 - -import ( - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/internal/protocol/restxml" - "github.com/awslabs/aws-sdk-go/internal/signer/v4" -) - -// S3 is a client for Amazon S3. -type S3 struct { - *aws.Service -} - -// Used for custom service initialization logic -var initService func(*aws.Service) - -// Used for custom request initialization logic -var initRequest func(*aws.Request) - -// New returns a new S3 client. -func New(config *aws.Config) *S3 { - if config == nil { - config = &aws.Config{} - } - - service := &aws.Service{ - Config: aws.DefaultConfig.Merge(config), - ServiceName: "s3", - APIVersion: "2006-03-01", - } - service.Initialize() - - // Handlers - service.Handlers.Sign.PushBack(v4.Sign) - service.Handlers.Build.PushBack(restxml.Build) - service.Handlers.Unmarshal.PushBack(restxml.Unmarshal) - service.Handlers.UnmarshalMeta.PushBack(restxml.UnmarshalMeta) - service.Handlers.UnmarshalError.PushBack(restxml.UnmarshalError) - - // Run custom service initialization if present - if initService != nil { - initService(service) - } - - return &S3{service} -} - -// newRequest creates a new request for a S3 operation and runs any -// custom request initialization. -func (c *S3) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { - req := aws.NewRequest(c.Service, op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse.go deleted file mode 100644 index 8977e3b8..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse.go +++ /dev/null @@ -1,46 +0,0 @@ -package s3 - -import ( - "crypto/md5" - "encoding/base64" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/aws/awsutil" -) - -var errSSERequiresSSL = aws.APIError{ - Code: "ConfigError", - Message: "cannot send SSE keys over HTTP.", -} - -func validateSSERequiresSSL(r *aws.Request) { - if r.HTTPRequest.URL.Scheme != "https" { - p := awsutil.ValuesAtPath(r.Params, "SSECustomerKey||CopySourceSSECustomerKey") - if len(p) > 0 { - r.Error = errSSERequiresSSL - } - } -} - -func computeSSEKeys(r *aws.Request) { - headers := []string{ - "x-amz-server-side-encryption-customer-key", - "x-amz-copy-source-server-side-encryption-customer-key", - } - - for _, h := range headers { - md5h := h + "-md5" - if key := r.HTTPRequest.Header.Get(h); key != "" { - // Base64-encode the value - b64v := base64.StdEncoding.EncodeToString([]byte(key)) - r.HTTPRequest.Header.Set(h, b64v) - - // Add MD5 if it wasn't computed - if r.HTTPRequest.Header.Get(md5h) == "" { - sum := md5.Sum([]byte(key)) - b64sum := base64.StdEncoding.EncodeToString(sum[:]) - r.HTTPRequest.Header.Set(md5h, b64sum) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse_test.go deleted file mode 100644 index f0e7b2b1..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/sse_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package s3_test - -import ( - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -func TestSSECustomerKeyOverHTTPError(t *testing.T) { - s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true})) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.Error(t, err) - aerr := aws.Error(err) - assert.Equal(t, "ConfigError", aerr.Code) - assert.Contains(t, aerr.Message, "cannot send SSE keys over HTTP") -} - -func TestCopySourceSSECustomerKeyOverHTTPError(t *testing.T) { - s := s3.New(baseConfig.Merge(&aws.Config{DisableSSL: true})) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - CopySourceSSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.Error(t, err) - aerr := aws.Error(err) - assert.Equal(t, "ConfigError", aerr.Code) - assert.Contains(t, aerr.Message, "cannot send SSE keys over HTTP") -} - -func TestComputeSSEKeys(t *testing.T) { - s := s3.New(baseConfig) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - CopySourceSSECustomerKey: aws.String("key"), - }) - err := req.Build() - - assert.NoError(t, err) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key")) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key")) - assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5")) - assert.Equal(t, "PG4LipwVIkqCKLmpjKFTHQ==", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5")) -} - -func TestComputeSSEKeysShortcircuit(t *testing.T) { - s := s3.New(baseConfig) - req, _ := s.CopyObjectRequest(&s3.CopyObjectInput{ - Bucket: aws.String("bucket"), - CopySource: aws.String("bucket/source"), - Key: aws.String("dest"), - SSECustomerKey: aws.String("key"), - CopySourceSSECustomerKey: aws.String("key"), - SSECustomerKeyMD5: aws.String("MD5"), - CopySourceSSECustomerKeyMD5: aws.String("MD5"), - }) - err := req.Build() - - assert.NoError(t, err) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key")) - assert.Equal(t, "a2V5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key")) - assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-server-side-encryption-customer-key-md5")) - assert.Equal(t, "MD5", req.HTTPRequest.Header.Get("x-amz-copy-source-server-side-encryption-customer-key-md5")) -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error.go deleted file mode 100644 index 9f3f1c72..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error.go +++ /dev/null @@ -1,41 +0,0 @@ -package s3 - -import ( - "encoding/xml" - "io" - "strings" - - "github.com/awslabs/aws-sdk-go/aws" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"Error"` - Code string `xml:"Code"` - Message string `xml:"Message"` -} - -func unmarshalError(r *aws.Request) { - defer r.HTTPResponse.Body.Close() - - if r.HTTPResponse.ContentLength == int64(0) { - // No body, use status code to generate an APIError - r.Error = aws.APIError{ - StatusCode: r.HTTPResponse.StatusCode, - Code: strings.Replace(r.HTTPResponse.Status, " ", "", -1), - Message: r.HTTPResponse.Status, - } - return - } - - resp := &xmlErrorResponse{} - err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) - if err != nil && err != io.EOF { - r.Error = err - } else { - r.Error = aws.APIError{ - StatusCode: r.HTTPResponse.StatusCode, - Code: resp.Code, - Message: resp.Message, - } - } -} diff --git a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error_test.go b/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error_test.go deleted file mode 100644 index 2e60a3c1..00000000 --- a/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/service/s3/unmarshal_error_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package s3_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/stretchr/testify/assert" -) - -var s3StatusCodeErrorTests = []struct { - scode int - status string - body string - code string - message string -}{ - {403, "Forbidden", "", "Forbidden", "Forbidden"}, - {400, "Bad Request", "", "BadRequest", "Bad Request"}, - {404, "Not Found", "", "NotFound", "Not Found"}, - {500, "Internal Error", "", "InternalError", "Internal Error"}, -} - -func TestStatusCodeError(t *testing.T) { - for _, test := range s3StatusCodeErrorTests { - s := s3.New(baseConfig) - s.Handlers.Send.Clear() - s.Handlers.Send.PushBack(func(r *aws.Request) { - body := ioutil.NopCloser(bytes.NewReader([]byte(test.body))) - r.HTTPResponse = &http.Response{ - ContentLength: int64(len(test.body)), - StatusCode: test.scode, - Status: test.status, - Body: body, - } - }) - _, err := s.PutBucketACL(&s3.PutBucketACLInput{ - Bucket: aws.String("bucket"), ACL: aws.String("public-read"), - }) - - assert.Error(t, err) - aerr := aws.Error(err) - assert.Equal(t, test.code, aerr.Code) - assert.Equal(t, test.message, aerr.Message) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/LICENSE b/Godeps/_workspace/src/github.com/clbanning/mxj/LICENSE deleted file mode 100644 index 67563f95..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -Copyright (c) 2012-2014 Charles Banning . All rights reserved. - -The MIT License (MIT) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -=============================================================================== - -Go Language Copyright & License - - -Copyright 2009 The Go Authors. All rights reserved. -Use of this source code is governed by a BSD-style -license that can be found in the LICENSE file. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml.go b/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml.go deleted file mode 100644 index 5579e103..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml.go +++ /dev/null @@ -1,177 +0,0 @@ -package mxj - -import ( - "encoding/xml" - "reflect" -) - -const ( - DefaultElementTag = "element" -) - -// Encode arbitrary value as XML. -// -// Note: unmarshaling the resultant -// XML may not return the original value, since tag labels may have been injected -// to create the XML representation of the value. -/* - Encode an arbitrary JSON object. - package main - - import ( - "encoding/json" - "fmt" - "github/clbanning/mxj" - ) - - func main() { - jsondata := []byte(`[ - { "somekey":"somevalue" }, - "string", - 3.14159265, - true - ]`) - var i interface{} - err := json.Unmarshal(jsondata, &i) - if err != nil { - // do something - } - x, err := anyxml.XmlIndent(i, "", " ", "mydoc") - if err != nil { - // do something else - } - fmt.Println(string(x)) - } - - output: - - somevalue - string - 3.14159265 - true - -*/ -// Alternative values for DefaultRootTag and DefaultElementTag can be set as: -// AnyXmlIndent( v, myRootTag, myElementTag). -func AnyXml(v interface{}, tags ...string) ([]byte, error) { - if reflect.TypeOf(v).Kind() == reflect.Struct { - return xml.Marshal(v) - } - - var err error - s := new(string) - p := new(pretty) - - var rt, et string - if len(tags) == 1 || len(tags) == 2 { - rt = tags[0] - } else { - rt = DefaultRootTag - } - if len(tags) == 2 { - et = tags[1] - } else { - et = DefaultElementTag - } - - var ss string - var b []byte - switch v.(type) { - case []interface{}: - ss = "<" + rt + ">" - for _, vv := range v.([]interface{}) { - switch vv.(type) { - case map[string]interface{}: - m := vv.(map[string]interface{}) - if len(m) == 1 { - for tag, val := range m { - err = mapToXmlIndent(false, s, tag, val, p) - } - } else { - err = mapToXmlIndent(false, s, et, vv, p) - } - default: - err = mapToXmlIndent(false, s, et, vv, p) - } - if err != nil { - break - } - } - ss += *s + "" - b = []byte(ss) - case map[string]interface{}: - m := Map(v.(map[string]interface{})) - b, err = m.Xml(rt) - default: - err = mapToXmlIndent(false, s, rt, v, p) - b = []byte(*s) - } - - return b, err -} - -// Encode an arbitrary value as a pretty XML string. -// Alternative values for DefaultRootTag and DefaultElementTag can be set as: -// AnyXmlIndent( v, "", " ", myRootTag, myElementTag). -func AnyXmlIndent(v interface{}, prefix, indent string, tags ...string) ([]byte, error) { - if reflect.TypeOf(v).Kind() == reflect.Struct { - return xml.MarshalIndent(v, prefix, indent) - } - - var err error - s := new(string) - p := new(pretty) - p.indent = indent - p.padding = prefix - - var rt, et string - if len(tags) == 1 || len(tags) == 2 { - rt = tags[0] - } else { - rt = DefaultRootTag - } - if len(tags) == 2 { - et = tags[1] - } else { - et = DefaultElementTag - } - - var ss string - var b []byte - switch v.(type) { - case []interface{}: - ss = "<" + rt + ">\n" - p.Indent() - for _, vv := range v.([]interface{}) { - switch vv.(type) { - case map[string]interface{}: - m := vv.(map[string]interface{}) - if len(m) == 1 { - for tag, val := range m { - err = mapToXmlIndent(true, s, tag, val, p) - } - } else { - p.start = 1 // we 1 tag in - err = mapToXmlIndent(true, s, et, vv, p) - *s += "\n" - } - default: - p.start = 0 // in case trailing p.start = 1 - err = mapToXmlIndent(true, s, et, vv, p) - } - if err != nil { - break - } - } - ss += *s + "" - b = []byte(ss) - case map[string]interface{}: - m := Map(v.(map[string]interface{})) - b, err = m.XmlIndent(prefix, indent, rt) - default: - err = mapToXmlIndent(true, s, rt, v, p) - b = []byte(*s) - } - - return b, err -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml_test.go deleted file mode 100644 index df722828..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/anyxml_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package mxj - -import ( - "encoding/json" - "fmt" - "testing" -) - -func TestAnyXmlHeader(t *testing.T) { - fmt.Println("\n---------------- anyxml_test.go ...\n") -} - -var anydata = []byte(`[ - { - "somekey": "somevalue" - }, - { - "somekey": "somevalue" - }, - { - "somekey": "somevalue", - "someotherkey": "someothervalue" - }, - "string", - 3.14159265, - true -]`) - -type MyStruct struct { - Somekey string `xml:"somekey"` - B float32 `xml:"floatval"` -} - -func TestAnyXml(t *testing.T) { - var i interface{} - err := json.Unmarshal(anydata, &i) - if err != nil { - t.Fatal(err) - } - x, err := AnyXml(i) - if err != nil { - t.Fatal(err) - } - fmt.Println("[]->x:", string(x)) - - a := []interface{}{"try", "this", 3.14159265, true} - x, err = AnyXml(a) - if err != nil { - t.Fatal(err) - } - fmt.Println("a->x:", string(x)) - - x, err = AnyXml(a, "myRootTag", "myElementTag") - if err != nil { - t.Fatal(err) - } - fmt.Println("a->x:", string(x)) - - x, err = AnyXml(3.14159625) - if err != nil { - t.Fatal(err) - } - fmt.Println("f->x:", string(x)) - - s := MyStruct{"somevalue", 3.14159625} - x, err = AnyXml(s) - if err != nil { - t.Fatal(err) - } - fmt.Println("s->x:", string(x)) -} - -func TestAnyXmlIndent(t *testing.T) { - var i interface{} - err := json.Unmarshal(anydata, &i) - if err != nil { - t.Fatal(err) - } - x, err := AnyXmlIndent(i, "", " ") - if err != nil { - t.Fatal(err) - } - fmt.Println("[]->x:\n", string(x)) - - a := []interface{}{"try", "this", 3.14159265, true} - x, err = AnyXmlIndent(a, "", " ") - if err != nil { - t.Fatal(err) - } - fmt.Println("a->x:\n", string(x)) - - x, err = AnyXmlIndent(3.14159625, "", " ") - if err != nil { - t.Fatal(err) - } - fmt.Println("f->x:\n", string(x)) - - x, err = AnyXmlIndent(3.14159625, "", " ", "myRootTag", "myElementTag") - if err != nil { - t.Fatal(err) - } - fmt.Println("f->x:\n", string(x)) - - s := MyStruct{"somevalue", 3.14159625} - x, err = AnyXmlIndent(s, "", " ") - if err != nil { - t.Fatal(err) - } - fmt.Println("s->x:\n", string(x)) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/bulk_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/bulk_test.go deleted file mode 100644 index bb64f9c0..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/bulk_test.go +++ /dev/null @@ -1,107 +0,0 @@ -// bulk_test.go - uses Handler and Writer functions to process some streams as a demo. - -package mxj - -import ( - "bytes" - "fmt" - "testing" -) - -func TestBulkHeader(t *testing.T) { - fmt.Println("\n---------------- bulk_test.go ...\n") -} - -var jsonWriter = new(bytes.Buffer) -var xmlWriter = new(bytes.Buffer) - -var jsonErrLog = new(bytes.Buffer) -var xmlErrLog = new(bytes.Buffer) - -func TestXmlReader(t *testing.T) { - // create Reader for xmldata - xmlReader := bytes.NewReader(xmldata) - - // read XML from Readerand pass Map value with the raw XML to handler - err := HandleXmlReader(xmlReader, bxmaphandler, bxerrhandler) - if err != nil { - t.Fatal("err:", err.Error()) - } - - // get the JSON - j := make([]byte, jsonWriter.Len()) - _, _ = jsonWriter.Read(j) - - // get the errors - e := make([]byte, xmlErrLog.Len()) - _, _ = xmlErrLog.Read(e) - - // print the input - fmt.Println("XmlReader, xmldata:\n", string(xmldata)) - // print the result - fmt.Println("XmlReader, result :\n", string(j)) - // print the errors - fmt.Println("XmlReader, errors :\n", string(e)) -} - -func bxmaphandler(m Map) bool { - j, err := m.JsonIndent("", " ", true) - if err != nil { - return false - } - - _, _ = jsonWriter.Write(j) - // put in a NL to pretty up printing the Writer - _, _ = jsonWriter.Write([]byte("\n")) - return true -} - -func bxerrhandler(err error) bool { - // write errors to file - _, _ = xmlErrLog.Write([]byte(err.Error())) - _, _ = xmlErrLog.Write([]byte("\n")) // pretty up - return true -} - -func TestJsonReader(t *testing.T) { - jsonReader := bytes.NewReader(jsondata) - - // read all the JSON - err := HandleJsonReader(jsonReader, bjmaphandler, bjerrhandler) - if err != nil { - t.Fatal("err:", err.Error()) - } - - // get the XML - x := make([]byte, xmlWriter.Len()) - _, _ = xmlWriter.Read(x) - - // get the errors - e := make([]byte, jsonErrLog.Len()) - _, _ = jsonErrLog.Read(e) - - // print the input - fmt.Println("JsonReader, jsondata:\n", string(jsondata)) - // print the result - fmt.Println("JsonReader, result :\n", string(x)) - // print the errors - fmt.Println("JsonReader, errors :\n", string(e)) -} - -func bjmaphandler(m Map) bool { - x, err := m.XmlIndent(" ", " ") - if err != nil { - return false - } - _, _ = xmlWriter.Write(x) - // put in a NL to pretty up printing the Writer - _, _ = xmlWriter.Write([]byte("\n")) - return true -} - -func bjerrhandler(err error) bool { - // write errors to file - _, _ = jsonErrLog.Write([]byte(err.Error())) - _, _ = jsonErrLog.Write([]byte("\n")) // pretty up - return true -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/bulkraw_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/bulkraw_test.go deleted file mode 100644 index 61c61fd5..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/bulkraw_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// bulk_test.go - uses Handler and Writer functions to process some streams as a demo. - -package mxj - -import ( - "bytes" - "fmt" - "testing" -) - -func TestBulkRawHeader(t *testing.T) { - fmt.Println("\n---------------- bulkraw_test.go ...\n") -} - -// use data from bulk_test.go - -var jsonWriterRaw = new(bytes.Buffer) -var xmlWriterRaw = new(bytes.Buffer) - -var jsonErrLogRaw = new(bytes.Buffer) -var xmlErrLogRaw = new(bytes.Buffer) - -func TestXmlReaderRaw(t *testing.T) { - // create Reader for xmldata - xmlReader := bytes.NewReader(xmldata) - - // read XML from Reader and pass Map value with the raw XML to handler - err := HandleXmlReaderRaw(xmlReader, bxmaphandlerRaw, bxerrhandlerRaw) - if err != nil { - t.Fatal("err:", err.Error()) - } - - // get the JSON - j := make([]byte, jsonWriterRaw.Len()) - _, _ = jsonWriterRaw.Read(j) - - // get the errors - e := make([]byte, xmlErrLogRaw.Len()) - _, _ = xmlErrLogRaw.Read(e) - - // print the input - fmt.Println("XmlReaderRaw, xmldata:\n", string(xmldata)) - // print the result - fmt.Println("XmlReaderRaw, result :\n", string(j)) - // print the errors - fmt.Println("XmlReaderRaw, errors :\n", string(e)) -} - -func bxmaphandlerRaw(m Map, raw []byte) bool { - j, err := m.JsonIndent("", " ", true) - if err != nil { - return false - } - - _, _ = jsonWriterRaw.Write(j) - // put in a NL to pretty up printing the Writer - _, _ = jsonWriterRaw.Write([]byte("\n")) - return true -} - -func bxerrhandlerRaw(err error, raw []byte) bool { - // write errors to file - _, _ = xmlErrLogRaw.Write([]byte(err.Error())) - _, _ = xmlErrLogRaw.Write([]byte("\n")) // pretty up - _, _ = xmlErrLogRaw.Write(raw) - _, _ = xmlErrLogRaw.Write([]byte("\n")) // pretty up - return true -} - -func TestJsonReaderRaw(t *testing.T) { - jsonReader := bytes.NewReader(jsondata) - - // read all the JSON - err := HandleJsonReaderRaw(jsonReader, bjmaphandlerRaw, bjerrhandlerRaw) - if err != nil { - t.Fatal("err:", err.Error()) - } - - // get the XML - x := make([]byte, xmlWriterRaw.Len()) - _, _ = xmlWriterRaw.Read(x) - - // get the errors - e := make([]byte, jsonErrLogRaw.Len()) - _, _ = jsonErrLogRaw.Read(e) - - // print the input - fmt.Println("JsonReaderRaw, jsondata:\n", string(jsondata)) - // print the result - fmt.Println("JsonReaderRaw, result :\n", string(x)) - // print the errors - fmt.Println("JsonReaderRaw, errors :\n", string(e)) -} - -func bjmaphandlerRaw(m Map, raw []byte) bool { - x, err := m.XmlIndent(" ", " ") - if err != nil { - return false - } - _, _ = xmlWriterRaw.Write(x) - // put in a NL to pretty up printing the Writer - _, _ = xmlWriterRaw.Write([]byte("\n")) - return true -} - -func bjerrhandlerRaw(err error, raw []byte) bool { - // write errors to file - _, _ = jsonErrLogRaw.Write([]byte(err.Error())) - _, _ = jsonErrLogRaw.Write([]byte("\n")) // pretty up, Error() from json.Unmarshal !NL - _, _ = jsonErrLogRaw.Write(raw) - _, _ = jsonErrLogRaw.Write([]byte("\n")) // pretty up - return true -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/data_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/data_test.go deleted file mode 100644 index 357513f6..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/data_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package mxj - -var xmldata = []byte(` - - William H. Gaddis - The Recognitions - One of the seminal American novels of the 20th century. - - - William H. Gaddis - JR - Won the National Book Award. - - - Austin Tappan Wright - Islandia - An example of earlier 20th century American utopian fiction. - - - John Hawkes - The Beetle Leg - A lyrical novel about the construction of Ft. Peck Dam in Montana. - - - - T.E. - Porter - - King's Day - A magical novella. -`) - -var jsondata = []byte(` - {"book":{"author":"William H. Gaddis","review":"One of the great seminal American novels of the 20th century.","title":"The Recognitions"}} -{"book":{"author":"Austin Tappan Wright","review":"An example of earlier 20th century American utopian fiction.","title":"Islandia"}} -{"book":{"author":"John Hawkes","review":"A lyrical novel about the construction of Ft. Peck Dam in Montana.","title":"The Beetle Leg"}} -{"book":{"author":{"first_name":"T.E.","last_name":"Porter"},"review":"A magical novella.","title":"King's Day"}} -{ "here":"we", "put":"in", "an":error }`) diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/doc.go b/Godeps/_workspace/src/github.com/clbanning/mxj/doc.go deleted file mode 100644 index 4db312c6..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/doc.go +++ /dev/null @@ -1,84 +0,0 @@ -// mxj - A collection of map[string]interface{} and associated XML and JSON utilities. -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -/* -Marshal/Unmarshal XML to/from JSON and map[string]interface{} values, and extract/modify values from maps by key or key-path, including wildcards. - -mxj supplants the legacy x2j and j2x packages. If you want the old syntax, use mxj/x2j or mxj/j2x packages. - -Note: this library was designed for processing ad hoc anonymous messages. Bulk processing large data sets may be much more efficiently performed using the encoding/xml or encoding/json packages from Go's standard library directly. - -Note: - 2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML. - -SUMMARY - - type Map map[string]interface{} - - Create a Map value, 'm', from any map[string]interface{} value, 'v': - m := Map(v) - - Unmarshal / marshal XML as a Map value, 'm': - m, err := NewMapXml(xmlValue) // unmarshal - xmlValue, err := m.Xml() // marshal - - Unmarshal XML from an io.Reader as a Map value, 'm': - m, err := NewMapReader(xmlReader) // repeated calls, as with an os.File Reader, will process stream - m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded - - Marshal Map value, 'm', to an XML Writer (io.Writer): - err := m.XmlWriter(xmlWriter) - raw, err := m.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter - - Also, for prettified output: - xmlValue, err := m.XmlIndent(prefix, indent, ...) - err := m.XmlIndentWriter(xmlWriter, prefix, indent, ...) - raw, err := m.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...) - - Bulk process XML with error handling (note: handlers must return a boolean value): - err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error)) - err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte)) - - Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader. - - There are comparable functions and methods for JSON processing. - - Arbitrary structure values can be decoded to / encoded from Map values: - m, err := NewMapStruct(structVal) - err := m.Struct(structPointer) - - To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON - or structure to a Map value, 'm', or cast a map[string]interface{} value to a Map value, 'm', then: - paths := m.PathsForKey(key) - path := m.PathForKeyShortest(key) - values, err := m.ValuesForKey(key, subkeys) - values, err := m.ValuesForPath(path, subkeys) // 'path' can be dot-notation with wildcards and indexed arrays. - count, err := m.UpdateValuesForPath(newVal, path, subkeys) - - Get everything at once, irrespective of path depth: - leafnodes := m.LeafNodes() - leafvalues := m.LeafValues() - - A new Map with whatever keys are desired can be created from the current Map and then encoded in XML - or JSON. (Note: keys can use dot-notation. 'oldKey' can also use wildcards and indexed arrays.) - newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N") - newXml := newMap.Xml() // for example - newJson := newMap.Json() // ditto - -XML PARSING CONVENTIONS - - - Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-', - to the attribute label. (PrependAttrWithHyphen(false) will override this.) - - If the element is a simple element and has attributes, the element value - is given the key '#text' for its map[string]interface{} representation. - -XML ENCODING CONVENTIONS - - - 'nil' Map values, which may represent 'null' JSON values, are encoded as "". - NOTE: the operation is not symmetric as "" elements are decoded as 'tag:""' Map values, - which, then, encode in JSON as '"tag":""' values.. - -*/ -package mxj diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/example_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/example_test.go deleted file mode 100644 index 81fb2861..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/example_test.go +++ /dev/null @@ -1,344 +0,0 @@ -// note - "// Output:" is a key for "go test" to match function ouput with the lines that follow. -// It is also use by "godoc" to build the Output block of the function / method documentation. -// To skip processing Example* functions, use: go test -run "Test*" -// or make sure example function output matches // Output: documentation EXACTLY. - -package mxj_test - -import ( - "bytes" - "fmt" - "github.com/clbanning/mxj" - "io" -) - -func ExampleHandleXmlReader() { - /* - Bulk processing XML to JSON seems to be a common requirement. - See: bulk_test.go for working example. - Run "go test" in package directory then scroll back to find output. - - The logic is as follows. - - // need somewhere to write the JSON. - var jsonWriter io.Writer - - // probably want to log any errors in reading the XML stream - var xmlErrLogger io.Writer - - // func to handle Map value from XML Reader - func maphandler(m mxj.Map) bool { - // marshal Map as JSON - jsonVal, err := m.Json() - if err != nil { - // log error - return false // stops further processing of XML Reader - } - - // write JSON somewhere - _, err = jsonWriter.Write(jsonVal) - if err != nil { - // log error - return false // stops further processing of XML Reader - } - - // continue - get next XML from Reader - return true - } - - // func to handle error from unmarshaling XML Reader - func errhandler(errVal error) bool { - // log error somewhere - _, err := xmlErrLogger.Write([]byte(errVal.Error())) - if err != nil { - // log error - return false // stops further processing of XML Reader - } - - // continue processing - return true - } - - // func that starts bulk processing of the XML - ... - // set up io.Reader for XML data - perhaps an os.File - ... - err := mxj.HandleXmlReader(xmlReader, maphandler, errhandler) - if err != nil { - // handle error - } - ... - */ -} - -func ExampleHandleXmlReaderRaw() { - /* - See: bulkraw_test.go for working example. - Run "go test" in package directory then scroll back to find output. - - Basic logic for bulk XML to JSON processing is in HandleXmlReader example; - the only major difference is in handler function signatures so they are passed - the raw XML. (Read documentation on NewXmlReader regarding performance.) - */ -} - -func ExampleHandleJsonReader() { - /* - See: bulk_test.go for working example. - Run "go test" in package directory then scroll back to find output. - - Basic logic for bulk JSON to XML processing is similar to that for - bulk XML to JSON processing as outlined in the HandleXmlReader example. - The test case is also a good example. - */ -} - -func ExampleHandleJsonReaderRaw() { - /* - See: bulkraw_test.go for working example. - Run "go test" in package directory then scroll back to find output. - - Basic logic for bulk JSON to XML processing is similar to that for - bulk XML to JSON processing as outlined in the HandleXmlReader example. - The test case is also a good example. - */ -} - -/* -func ExampleNewMapXmlReaderRaw() { - // in an http.Handler - - mapVal, raw, err := mxj.NewMapXmlReader(req.Body) - if err != nil { - // handle error - } - logger.Print(string(*raw)) - // do something with mapVal - -} -*/ - -func ExampleNewMapStruct() { - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - private string - } - strVal := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"} - - mapVal, merr := mxj.NewMapStruct(strVal) - if merr != nil { - // handle error - } - - fmt.Printf("strVal: %#v\n", strVal) - fmt.Printf("mapVal: %#v\n", mapVal) - // Note: example output is conformed to pass "go test". "mxj_test" is example_test.go package name. - - // Output: - // strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"} - // mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true} -} - -func ExampleMap_Struct() { - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - private string - } - - mapVal := mxj.Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true, "private": "Somewhere over the rainbow"} - - var strVal str - mverr := mapVal.Struct(&strVal) - if mverr != nil { - // handle error - } - - fmt.Printf("mapVal: %#v\n", mapVal) - fmt.Printf("strVal: %#v\n", strVal) - // Note: example output is conformed to pass "go test". "mxj_test" is example_test.go package name. - - // Output: - // mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true, "private":"Somewhere over the rainbow"} - // strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:""} -} - -func ExampleMap_ValuesForKeyPath() { - // a snippet from examples/gonuts1.go - // How to compensate for irregular tag labels in data. - // Need to extract from an XML stream the values for "netid" and "idnet". - // Solution: use a wildcard path "data.*" to anonymize the "netid" and "idnet" tags. - - var msg1 = []byte(` - - - - no - default:text - default:word - - -`) - - var msg2 = []byte(` - - - - yes - default:text - default:word - - -`) - - // let's create a message stream - buf := new(bytes.Buffer) - // load a couple of messages into it - _, _ = buf.Write(msg1) - _, _ = buf.Write(msg2) - - n := 0 - for { - n++ - // Read the stream as Map values - quit on io.EOF. - // Get the raw XML as well as the Map value. - m, merr := mxj.NewMapXmlReader(buf) - if merr != nil && merr != io.EOF { - // handle error - for demo we just print it and continue - fmt.Printf("msg: %d - merr: %s\n", n, merr.Error()) - continue - } else if merr == io.EOF { - break - } - - // get the values for "netid" or "idnet" key using path == "data.*" - values, _ := m.ValuesForPath("data.*") - fmt.Println("\nmsg:", n, "> path == data.* - got array of values, len:", len(values)) - for i, val := range values { - fmt.Println("ValuesForPath result array member -", i, ":", val) - fmt.Println(" k:v pairs for array member:", i) - for key, val := range val.(map[string]interface{}) { - // You'd probably want to process the value, as appropriate. - // Here we just print it out. - fmt.Println("\t\t", key, ":", val) - } - } - } - // Output: - // msg: 1 > path == data.* - got array of values, len: 1 - // ValuesForPath result array member - 0 : map[disable:no text1:default:text word1:default:word] - // k:v pairs for array member: 0 - // disable : no - // text1 : default:text - // word1 : default:word - // - // msg: 2 > path == data.* - got array of values, len: 1 - // ValuesForPath result array member - 0 : map[disable:yes text1:default:text word1:default:word] - // k:v pairs for array member: 0 - // disable : yes - // text1 : default:text - // word1 : default:word -} - -func ExampleMap_UpdateValuesForPath() { - /* - - var biblioDoc = []byte(` - - - William Gaddis - - - The Recognitions - 1955 - A novel that changed the face of American literature. - - - JR - 1975 - Winner of National Book Award for Fiction. - - - - `) - - ... - m, merr := mxj.NewMapXml(biblioDoc) - if merr != nil { - // handle error - } - - // change 'review' for a book - count, err := m.UpdateValuesForPath("review:National Book Award winner." "*.*.*.*", "title:JR") - if err != nil { - // handle error - } - ... - - // change 'date' value from string type to float64 type - // Note: the following is equivalent to m, merr := NewMapXml(biblioDoc, mxj.Cast). - path := m.PathForKeyShortest("date") - v, err := m.ValuesForPath(path) - if err != nil { - // handle error - } - var total int - for _, vv := range v { - oldVal := "date:" + vv.(string) - newVal := "date:" + vv.(string) + ":num" - n, err := m.UpdateValuesForPath(newVal, path, oldVal) - if err != nil { - // handle error - } - total += n - } - ... - */ -} - -func ExampleMap_Copy() { - // Hand-crafted Map values that include structures do NOT Copy() as expected, - // since to simulate a deep copy the original Map value is JSON encoded then decoded. - - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - private string - } - s := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"} - m := make(map[string]interface{}, 0) - m["struct"] = interface{}(s) - m["struct_ptr"] = interface{}(&s) - m["misc"] = interface{}(`Now is the time`) - - mv := mxj.Map(m) - cp, _ := mv.Copy() - - fmt.Printf("mv:%s\n", mv.StringIndent(2)) - fmt.Printf("cp:%s\n", cp.StringIndent(2)) - - // Output: - // mv: - // struct :[unknown] mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"} - // struct_ptr :[unknown] &mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"} - // misc :[string] Now is the time - // cp: - // misc :[string] Now is the time - // struct : - // int :[float64] 4.00e+00 - // str :[string] now's the time - // float :[float64] 3.14e+00 - // bool :[bool] true - // struct_ptr : - // int :[float64] 4.00e+00 - // str :[string] now's the time - // float :[float64] 3.14e+00 - // bool :[bool] true -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/README b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/README deleted file mode 100644 index e14580f7..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/README +++ /dev/null @@ -1,124 +0,0 @@ -Examples of using ValuesFromTagPath(). - -A number of interesting examples have shown up in the gonuts discussion group -that could be handled - after a fashion - using the ValuesFromTagPath() function. - -gonuts1.go - - -Here we see that the message stream has a problem with multiple tag spellings, -though the message structure remains constant. In this example we 'anonymize' -the tag for the variant spellings. - values := m.ValuesForPath("data.*) - where '*' is any possible spelling - "netid" or "idnet" - and the result is a list with 1 member of map[string]interface{} type. - -Once we've retrieved the Map, we can parse it using the known keys - "disable", -"text1" and "word1". - - -gonuts1a.go - (03-mar-14) - -Here we just permute the tag labels using m.NewMap() to make all the messages -consistent. Then they can be decoded into a single structure definition. - - -gonuts2.go - - -This is an interesting case where there was a need to handle messages with lists -of "ClaimStatusCodeRecord" entries as well as messages with NONE. (Here we see -some of the vagaries of dealing with mixed messages that are verging on becoming -anonymous.) - - msg1 - the message with two ClaimStatusCodeRecord entries - msg2 - the message with one ClaimStatusCodeRecord entry - msg3 - the message with NO ClaimStatusCodeRecord entries - -ValuesForPath options: - - path == "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord" - for msg == msg1: - returns: a list - []interface{} - with two values of map[string]interface{} type - for msg == msg2: - returns: a list - []interface{} - with one map[string]interface{} type - for msg == msg3: - returns 'nil' - no values - - path == "*.*.*.*.*" - for msg == msg1: - returns: a list - []interface{} - with two values of map[string]interface{} type - - path == "*.*.*.*.*.Description - for msg == msg1: - returns: a list - []interface{} - with two values of string type, the individual - values from parsing the two map[string]interface{} values where key=="Description" - - path == "*.*.*.*.*.*" - for msg == msg1: - returns: a list - []interface{} - with six values of string type, the individual - values from parsing all keys in the two map[string]interface{} values - -Think of the wildcard character "*" as anonymizing the tag in the position of the path where -it occurs. The books.go example has a range of use cases. - - -gonuts3.go - - -Uses the ValuesForKey method to extract a list of image "src" file names that are encoded as -attribute values. - - -gonuts4.go - - -Here we use the ValuesForPath to extract attribute values for country names. The attribute -is included in the 'path' argument by prepending it with a hyphen: ""doc.some_tag.geoInfo.country.-name". - - -gonuts5.go (10-mar-14) - - -Extract a node of values using ValuesForPath based on name="list3-1-1-1". Then get the values -for the 'int' entries based on attribute 'name' values - mv.ValuesForKey("int", "-name:"+n). - -gonuts5a.go (10-mar-14) - - -Extract a node of values using ValuesForPath based on name="list3-1-1-1". Then get the values -for the 'int' entries based on attribute 'name' values - mv.ValuesForKey("*", "-name:"+n). -(Same as gonuts5.go but with wildcarded key value, since we're matching elements on subkey.) - - -EAT YOUR OWN DOG FOOD ... - -I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an -application that had 355,100 lines of code in 211 packages into CSV data sets. The report -included application-, package-, class- and method-level metrics reported in an element, -"Value", with varying attributes. - - - - - -In addition, the metrics were reported with two different "Metric" compound elements: - - - - - ... - - - ... - - - - ... - - -Using the mxj package seemed a more straightforward approach than using Go vernacular -and the standard xml package. I wrote the program getmetrics.go to do this. Here are -three version to illustrate using - getmetrics1.go - pass os.File handle for metrics_data.xml to NewMapXmlReader. - getmetrics2.go - load metrics_data.xml into an in-memory buffer, then pass it to NewMapXml. - getmetrics3.go - demonstrates overhead of extracting the raw XML while decoding with NewMapXmlReaderRaw. - -To run example getmetrics1.go, extract a 120,000+ row data set from metrics_data.zip. Then: - go run getmetrics1.go -file=metrics_data.xml - - diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/books.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/books.go deleted file mode 100644 index e703d839..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/books.go +++ /dev/null @@ -1,71 +0,0 @@ -// Note: this illustrates ValuesForKey() and ValuesForPath() methods - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" - "log" -) - -var xmldata = []byte(` - - - William H. Gaddis - The Recognitions - One of the great seminal American novels of the 20th century. - - - Austin Tappan Wright - Islandia - An example of earlier 20th century American utopian fiction. - - - John Hawkes - The Beetle Leg - A lyrical novel about the construction of Ft. Peck Dam in Montana. - - - T.E. Porter - King's Day - A magical novella. - - -`) - -func main() { - fmt.Println(string(xmldata)) - - m, err := mxj.NewMapXml(xmldata) - if err != nil { - log.Fatal("err:", err.Error()) - } - - v, _ := m.ValuesForKey("books") - fmt.Println("path: books; len(v):", len(v)) - fmt.Printf("\t%+v\n", v) - - v, _ = m.ValuesForPath("books.book") - fmt.Println("path: books.book; len(v):", len(v)) - for _, vv := range v { - fmt.Printf("\t%+v\n", vv) - } - - v, _ = m.ValuesForPath("books.*") - fmt.Println("path: books.*; len(v):", len(v)) - for _, vv := range v { - fmt.Printf("\t%+v\n", vv) - } - - v, _ = m.ValuesForPath("books.*.title") - fmt.Println("path: books.*.title len(v):", len(v)) - for _, vv := range v { - fmt.Printf("\t%+v\n", vv) - } - - v, _ = m.ValuesForPath("books.*.*") - fmt.Println("path: books.*.*; len(v):", len(v)) - for _, vv := range v { - fmt.Printf("\t%+v\n", vv) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics1.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics1.go deleted file mode 100644 index c4e68038..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics1.go +++ /dev/null @@ -1,176 +0,0 @@ -// getmetrics1.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric -// Uses NewMapXmlReader on os.File without copying the raw XML into a buffer while decoding.. -// Shows no significant overhead for not first buffering large XML file as in getmetrics2.go. - -/* -I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an -application that had 355,100 lines of code in 211 packages into CSV data sets. The report -included application-, package-, class- and method-level metrics reported in an element, -"Value", with varying attributes. - - - - - -In addition, the metrics were reported with two different "Metric" compound elements: - - - - - ... - - - ... - - - - ... - - -To run this example, extract the metrics_data.xml file from metrics_data.zip, then: - > go run getmetrics1 -file=metrics_data.xml - -The output will be a set of "csv" files. -*/ - -package main - -import ( - "flag" - "fmt" - "github.com/clbanning/mxj" - "log" - "os" - "time" -) - -func main() { - var file string - flag.StringVar(&file, "file", "", "file to process") - flag.Parse() - - fh, fherr := os.Open(file) - if fherr != nil { - fmt.Println("fherr:", fherr.Error()) - return - } - defer fh.Close() - fmt.Println(time.Now().String(), "... File Opened:", file) - - /* - // Get the XML data set from the file. - fs, _ := fh.Stat() - xmldata := make([]byte, fs.Size()) - n, frerr := fh.Read(xmldata) - if frerr != nil { - fmt.Println("frerr:", frerr.Error()) - return - } - if int64(n) != fs.Size() { - fmt.Println("n:", n, "fs.Size():", fs.Size()) - return - } - fmt.Println(time.Now().String(), "... File Read - size:", fs.Size()) - - // load XML into a Map value - m, merr := mxj.NewMapXml(xmldata) - */ - // Consume the file using os.File Reader. - // Note: there is a single record with root tag of "Metrics". - m, merr := mxj.NewMapXmlReader(fh) - if merr != nil { - log.Fatal("merr:", merr.Error()) - } - fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m)) - - // Get just the key values of interest. - // Could also use m.ValuesForKey("Metric"), - // since there's just the one path. - metricVals, err := m.ValuesForPath("Metrics.Metric") - if err != nil { - log.Fatal("err:", err.Error()) - } - fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals)) - - // now just manipulate Map entries returned as []interface{} array. - for _, v := range metricVals { - aMetricVal := v.(map[string]interface{}) - - // create file to hold csv data sets - id := aMetricVal["-id"].(string) - desc := aMetricVal["-description"].(string) - mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) - if mferr != nil { - fmt.Println("mferr:", mferr.Error()) - return - } - - fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc) - mf.WriteString(id + "," + desc + "\n") - - // rescan looking for keys with data: Values or Value - for key, val := range aMetricVal { - switch key { - case "Values": - // extract the list of "Value" from map - values := val.(map[string]interface{})["Value"].([]interface{}) - fmt.Println(" len(Values):", len(values)) - - // first line in file is the metric label values (keys) - var gotKeys bool - for _, vval := range values { - valueEntry := vval.(map[string]interface{}) - - // no guarantee that range on map will follow any sequence - lv := len(valueEntry) - type ev [2]string - list := make([]ev, lv) - var i int - for k, v := range valueEntry { - list[i][0] = k - list[i][1] = v.(string) - i++ - } - - // extract keys as column header on first pass - if !gotKeys { - // print out the keys - var gotFirstKey bool - // for kk, _ := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstKey { - mf.WriteString(",") - } else { - gotFirstKey = true - } - // strip prepended hyphen - mf.WriteString((list[i][0])[1:]) - } - mf.WriteString("\n") - gotKeys = true - } - - // print out values - var gotFirstVal bool - // for _, vv := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstVal { - mf.WriteString(",") - } else { - gotFirstVal = true - } - mf.WriteString(list[i][1]) - } - - // terminate row of data - mf.WriteString("\n") - } - case "Value": - vv := val.(map[string]interface{}) - fmt.Println(" len(Value):", len(vv)) - mf.WriteString("value\n" + vv["-value"].(string) + "\n") - } - } - mf.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics2.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics2.go deleted file mode 100644 index 65d6c951..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics2.go +++ /dev/null @@ -1,173 +0,0 @@ -// getmetrics2.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric -// Uses an in-memory buffer for the XML data and direct XML decoding of the buffer into a Map. -// Not significantly faster than getmetrics1.go that uses an io.Reader (os.File) to directly -// decode the XML from the file. - -/* -I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an -application that had 355,100 lines of code in 211 packages into CSV data sets. The report -included application-, package-, class- and method-level metrics reported in an element, -"Value", with varying attributes. - - - - - -In addition, the metrics were reported with two different "Metric" compound elements: - - - - - ... - - - ... - - - - ... - - -To run this example, extract the metrics_data.xml file from metrics_data.zip, then: - > go run getmetrics -file=metrics_data.xml - -The output will be a set of "csv" files. -*/ - -package main - -import ( - "flag" - "fmt" - "github.com/clbanning/mxj" - "log" - "os" - "time" -) - -func main() { - var file string - flag.StringVar(&file, "file", "", "file to process") - flag.Parse() - - fh, fherr := os.Open(file) - if fherr != nil { - fmt.Println("fherr:", fherr.Error()) - return - } - defer fh.Close() - fmt.Println(time.Now().String(), "... File Opened:", file) - - // Get the XML data set from the file. - fs, _ := fh.Stat() - xmldata := make([]byte, fs.Size()) - n, frerr := fh.Read(xmldata) - if frerr != nil { - fmt.Println("frerr:", frerr.Error()) - return - } - if int64(n) != fs.Size() { - fmt.Println("n:", n, "fs.Size():", fs.Size()) - return - } - fmt.Println(time.Now().String(), "... File Read - size:", fs.Size()) - - // load XML into a Map value - // Note: there is a single record with root tag of "Metrics". - m, merr := mxj.NewMapXml(xmldata) - if merr != nil { - log.Fatal("merr:", merr.Error()) - } - fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m)) - - // Get just the key values of interest. - // Could also use m.ValuesForKey("Metric"), - // since there's just the one path. - metricVals, err := m.ValuesForPath("Metrics.Metric") - if err != nil { - log.Fatal("err:", err.Error()) - } - fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals)) - - // now just manipulate Map entries returned as []interface{} array. - for _, v := range metricVals { - aMetricVal := v.(map[string]interface{}) - - // create file to hold csv data sets - id := aMetricVal["-id"].(string) - desc := aMetricVal["-description"].(string) - mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) - if mferr != nil { - fmt.Println("mferr:", mferr.Error()) - return - } - - fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc) - mf.WriteString(id + "," + desc + "\n") - - // rescan looking for keys with data: Values or Value - for key, val := range aMetricVal { - switch key { - case "Values": - // extract the list of "Value" from map - values := val.(map[string]interface{})["Value"].([]interface{}) - fmt.Println(" len(Values):", len(values)) - - // first line in file is the metric label values (keys) - var gotKeys bool - for _, vval := range values { - valueEntry := vval.(map[string]interface{}) - - // no guarantee that range on map will follow any sequence - lv := len(valueEntry) - type ev [2]string - list := make([]ev, lv) - var i int - for k, v := range valueEntry { - list[i][0] = k - list[i][1] = v.(string) - i++ - } - - // extract keys as column header on first pass - if !gotKeys { - // print out the keys - var gotFirstKey bool - // for kk, _ := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstKey { - mf.WriteString(",") - } else { - gotFirstKey = true - } - // strip prepended hyphen - mf.WriteString((list[i][0])[1:]) - } - mf.WriteString("\n") - gotKeys = true - } - - // print out values - var gotFirstVal bool - // for _, vv := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstVal { - mf.WriteString(",") - } else { - gotFirstVal = true - } - mf.WriteString(list[i][1]) - } - - // terminate row of data - mf.WriteString("\n") - } - case "Value": - vv := val.(map[string]interface{}) - fmt.Println(" len(Value):", len(vv)) - mf.WriteString("value\n" + vv["-value"].(string) + "\n") - } - } - mf.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics3.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics3.go deleted file mode 100644 index a914d549..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics3.go +++ /dev/null @@ -1,180 +0,0 @@ -// getmetrics3.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric -// Uses NewMapXmlReaderRaw that requires loading raw XML into a []byte buffer using a ByteReader. -// Show's performance impact of copying the raw XML while simultaneously decoding it from on os.File -// Reader. (vs. getmetrics1.go) If you're processing a file and need a copy of the raw XML and SPEED, -// should buffer the file in memory and decode using mxj.NewMapXmlReaderRaw as in getmetrics4.go. - -/* -I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an -application that had 355,100 lines of code in 211 packages into CSV data sets. The report -included application-, package-, class- and method-level metrics reported in an element, -"Value", with varying attributes. - - - - - -In addition, the metrics were reported with two different "Metric" compound elements: - - - - - ... - - - ... - - - - ... - - -To run this example, extract the metrics_data.xml file from metrics_data.zip, then: - > go run getmetrics3 -file=metrics_data.xml - -The output will be a set of "csv" files. -*/ - -package main - -import ( - "flag" - "fmt" - "github.com/clbanning/mxj" - "log" - "os" - "time" -) - -func main() { - var file string - flag.StringVar(&file, "file", "", "file to process") - flag.Parse() - - fh, fherr := os.Open(file) - if fherr != nil { - fmt.Println("fherr:", fherr.Error()) - return - } - defer fh.Close() - fmt.Println(time.Now().String(), "... File Opened:", file) - - /* - // Get the XML data set from the file. - fs, _ := fh.Stat() - xmldata := make([]byte, fs.Size()) - n, frerr := fh.Read(xmldata) - if frerr != nil { - fmt.Println("frerr:", frerr.Error()) - return - } - if int64(n) != fs.Size() { - fmt.Println("n:", n, "fs.Size():", fs.Size()) - return - } - fmt.Println(time.Now().String(), "... File Read - size:", fs.Size()) - - // load XML into a Map value - m, merr := mxj.NewMapXml(xmldata) - */ - // Consume the file using os.File Reader. - // Note: there is a single record with root tag of "Metrics". - // Also: this is MUCH slower than using buffer or not loading raw XML. - m, raw, merr := mxj.NewMapXmlReaderRaw(fh) - if merr != nil { - log.Fatal("merr:", merr.Error()) - } - fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m)) - fmt.Println("raw XML buffer size (should be same as File size):", len(*raw)) - - // Get just the key values of interest. - // Could also use m.ValuesForKey("Metric"), - // since there's just the one path. - metricVals, err := m.ValuesForPath("Metrics.Metric") - if err != nil { - log.Fatal("err:", err.Error()) - } - fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals)) - - // now just manipulate Map entries returned as []interface{} array. - for _, v := range metricVals { - aMetricVal := v.(map[string]interface{}) - - // create file to hold csv data sets - id := aMetricVal["-id"].(string) - desc := aMetricVal["-description"].(string) - mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) - if mferr != nil { - fmt.Println("mferr:", mferr.Error()) - return - } - - fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc) - mf.WriteString(id + "," + desc + "\n") - - // rescan looking for keys with data: Values or Value - for key, val := range aMetricVal { - switch key { - case "Values": - // extract the list of "Value" from map - values := val.(map[string]interface{})["Value"].([]interface{}) - fmt.Println(" len(Values):", len(values)) - - // first line in file is the metric label values (keys) - var gotKeys bool - for _, vval := range values { - valueEntry := vval.(map[string]interface{}) - - // no guarantee that range on map will follow any sequence - lv := len(valueEntry) - type ev [2]string - list := make([]ev, lv) - var i int - for k, v := range valueEntry { - list[i][0] = k - list[i][1] = v.(string) - i++ - } - - // extract keys as column header on first pass - if !gotKeys { - // print out the keys - var gotFirstKey bool - // for kk, _ := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstKey { - mf.WriteString(",") - } else { - gotFirstKey = true - } - // strip prepended hyphen - mf.WriteString((list[i][0])[1:]) - } - mf.WriteString("\n") - gotKeys = true - } - - // print out values - var gotFirstVal bool - // for _, vv := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstVal { - mf.WriteString(",") - } else { - gotFirstVal = true - } - mf.WriteString(list[i][1]) - } - - // terminate row of data - mf.WriteString("\n") - } - case "Value": - vv := val.(map[string]interface{}) - fmt.Println(" len(Value):", len(vv)) - mf.WriteString("value\n" + vv["-value"].(string) + "\n") - } - } - mf.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics4.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics4.go deleted file mode 100644 index 2cf66381..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/getmetrics4.go +++ /dev/null @@ -1,179 +0,0 @@ -// getmetrics2.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric -// Uses an in-memory buffer for the XML data and direct XML decoding of the buffer into a Map. -// Then XML buffer is decoded into a Map while the raw XML is copied using NewMapXmlReaderRaw() -// to illustrate processing overhead relative to getmetrics2.go. Not a practical example, -// but confirms the getmetrics1.go vs. getmetrics3.go use case. - -/* -I needed to convert a large (14.9 MB) XML data set from an Eclipse metrics report on an -application that had 355,100 lines of code in 211 packages into CSV data sets. The report -included application-, package-, class- and method-level metrics reported in an element, -"Value", with varying attributes. - - - - - -In addition, the metrics were reported with two different "Metric" compound elements: - - - - - ... - - - ... - - - - ... - - -To run this example, extract the metrics_data.xml file from metrics_data.zip, then: - > go run getmetrics -file=metrics_data.xml - -The output will be a set of "csv" files. -*/ - -package main - -import ( - "bytes" - "flag" - "fmt" - "github.com/clbanning/mxj" - "log" - "os" - "time" -) - -func main() { - var file string - flag.StringVar(&file, "file", "", "file to process") - flag.Parse() - - fh, fherr := os.Open(file) - if fherr != nil { - fmt.Println("fherr:", fherr.Error()) - return - } - defer fh.Close() - fmt.Println(time.Now().String(), "... File Opened:", file) - - // Get the XML data set from the file. - fs, _ := fh.Stat() - xmldata := make([]byte, fs.Size()) - n, frerr := fh.Read(xmldata) - if frerr != nil { - fmt.Println("frerr:", frerr.Error()) - return - } - if int64(n) != fs.Size() { - fmt.Println("n:", n, "fs.Size():", fs.Size()) - return - } - fmt.Println(time.Now().String(), "... File Read - size:", fs.Size()) - - // wrap the buffer in an io.Reader - xmlReader := bytes.NewBuffer(xmldata) - - // load XML into a Map value - // Note: there is a single record with root tag of "Metrics". - m, raw, merr := mxj.NewMapXmlReaderRaw(xmlReader) // don't catch the pointer to raw XML - if merr != nil { - log.Fatal("merr:", merr.Error()) - } - fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m)) - fmt.Println("raw XML buffer size (should be same as File size):", len(*raw)) - - // Get just the key values of interest. - // Could also use m.ValuesForKey("Metric"), - // since there's just the one path. - metricVals, err := m.ValuesForPath("Metrics.Metric") - if err != nil { - log.Fatal("err:", err.Error()) - } - fmt.Println(time.Now().String(), "... ValuesFromKeyPath - len:", len(metricVals)) - - // now just manipulate Map entries returned as []interface{} array. - for _, v := range metricVals { - aMetricVal := v.(map[string]interface{}) - - // create file to hold csv data sets - id := aMetricVal["-id"].(string) - desc := aMetricVal["-description"].(string) - mf, mferr := os.OpenFile(id+".csv", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) - if mferr != nil { - fmt.Println("mferr:", mferr.Error()) - return - } - - fmt.Print(time.Now().String(), " id: ", id, " desc: ", desc) - mf.WriteString(id + "," + desc + "\n") - - // rescan looking for keys with data: Values or Value - for key, val := range aMetricVal { - switch key { - case "Values": - // extract the list of "Value" from map - values := val.(map[string]interface{})["Value"].([]interface{}) - fmt.Println(" len(Values):", len(values)) - - // first line in file is the metric label values (keys) - var gotKeys bool - for _, vval := range values { - valueEntry := vval.(map[string]interface{}) - - // no guarantee that range on map will follow any sequence - lv := len(valueEntry) - type ev [2]string - list := make([]ev, lv) - var i int - for k, v := range valueEntry { - list[i][0] = k - list[i][1] = v.(string) - i++ - } - - // extract keys as column header on first pass - if !gotKeys { - // print out the keys - var gotFirstKey bool - // for kk, _ := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstKey { - mf.WriteString(",") - } else { - gotFirstKey = true - } - // strip prepended hyphen - mf.WriteString((list[i][0])[1:]) - } - mf.WriteString("\n") - gotKeys = true - } - - // print out values - var gotFirstVal bool - // for _, vv := range valueEntry { - for i := 0; i < lv; i++ { - if gotFirstVal { - mf.WriteString(",") - } else { - gotFirstVal = true - } - mf.WriteString(list[i][1]) - } - - // terminate row of data - mf.WriteString("\n") - } - case "Value": - vv := val.(map[string]interface{}) - fmt.Println(" len(Value):", len(vv)) - mf.WriteString("value\n" + vv["-value"].(string) + "\n") - } - } - mf.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1.go deleted file mode 100644 index a0c5d6fc..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1.go +++ /dev/null @@ -1,82 +0,0 @@ -// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ -// http://play.golang.org/p/BFFDxphKYK - -package main - -import ( - "bytes" - "fmt" - "github.com/clbanning/mxj" - "io" -) - -// Demo how to compensate for irregular tag labels in data. -// Need to extract from an XML stream the values for "netid" and "idnet". -// Solution: use a wildcard path "data.*" to anonymize the "netid" and "idnet" tags. - -var msg1 = []byte(` - - - - no - default:text - default:word - - -`) - -var msg2 = []byte(` - - - - yes - default:text - default:word - - -`) - -func main() { - // let's create a message stream - buf := new(bytes.Buffer) - // load a couple of messages into it - _, _ = buf.Write(msg1) - _, _ = buf.Write(msg2) - - n := 0 - for { - n++ - // read the stream as Map values - quit on io.EOF - m, raw, merr := mxj.NewMapXmlReaderRaw(buf) - if merr != nil && merr != io.EOF { - // handle error - for demo we just print it and continue - fmt.Printf("msg: %d - merr: %s\n", n, merr.Error()) - continue - } else if merr == io.EOF { - break - } - fmt.Println("\nMessage to parse:", string(*raw)) - fmt.Println("Map value for XML message:", m.StringIndent()) - - // get the values for "netid" or "idnet" key using path == "data.*" - values, _ := m.ValuesForPath("data.*") - fmt.Println("\nmsg:", n, "> path == data.* - got array of values, len:", len(values)) - for i, val := range values { - fmt.Println("ValuesForPath result array member -", i, ":", val) - fmt.Println(" k:v pairs for array member:", i) - for key, val := range val.(map[string]interface{}) { - // You'd probably want to process the value, as appropriate. - // Here we just print it out. - fmt.Println("\t\t", key, ":", val) - } - } - - // This shows what happens if you wildcard the value keys for "idnet" and "netid" - values, _ = m.ValuesForPath("data.*.*") - fmt.Println("\npath == data.*.* - got an array of values, len(v):", len(values)) - fmt.Println("(Note: values returned by ValuesForPath are at maximum depth of the tree. So just have values.)") - for i, val := range values { - fmt.Println("ValuesForPath array member -", i, ":", val) - } - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1a.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1a.go deleted file mode 100644 index fbe58ffa..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts1a.go +++ /dev/null @@ -1,68 +0,0 @@ -// https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ -// http://play.golang.org/p/BFFDxphKYK - -package main - -import ( - "bytes" - "fmt" - "github.com/clbanning/mxj" - "io" -) - -// Demo how to re-label a key using mv.NewMap(). -// Need to normalize from an XML stream the tags "netid" and "idnet". -// Solution: make everything "netid". - -var msg1 = []byte(` - - - - no - default:text - default:word - - -`) - -var msg2 = []byte(` - - - - yes - default:text - default:word - - -`) - -func main() { - // let's create a message stream - buf := new(bytes.Buffer) - // load a couple of messages into it - _, _ = buf.Write(msg1) - _, _ = buf.Write(msg2) - - n := 0 - for { - n++ - // read the stream as Map values - quit on io.EOF - m, raw, merr := mxj.NewMapXmlReaderRaw(buf) - if merr != nil && merr != io.EOF { - // handle error - for demo we just print it and continue - fmt.Printf("msg: %d - merr: %s\n", n, merr.Error()) - continue - } else if merr == io.EOF { - break - } - - // the first keypair retains values if data correct - // the second keypair relabels "idnet" to "netid" - n, _ := m.NewMap("data.netid", "data.idnet:data.netid") - x, _ := n.XmlIndent("", " ") - - fmt.Println("original value:", string(raw)) - fmt.Println("new value:") - fmt.Println(string(x)) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts2.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts2.go deleted file mode 100644 index 6bd0bab7..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts2.go +++ /dev/null @@ -1,240 +0,0 @@ -// https://groups.google.com/forum/#!topic/golang-nuts/V83jUKluLnM -// http://play.golang.org/p/alWGk4MDBc - -// Here messsages come in one of three forms: -// ... list of ClaimStatusCodeRecord ... -// ... one instance of ClaimStatusCodeRecord ... -// ... empty element ... -// ValueForPath - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" -) - -var xmlmsg1 = []byte(` - - - - -true -A -Initial Claim Review/Screening - - -true -B -Initial Contact Made w/ Provider - - - - - -`) - -var xmlmsg2 = []byte(` - - - - -true -A -Initial Claim Review/Screening - - - - - -`) - -var xmlmsg3 = []byte(` - - - - - - - -`) - -func main() { - xmldata := [][]byte{xmlmsg1, xmlmsg2, xmlmsg3} - fullPath(xmldata) - partPath1(xmlmsg1) - partPath2(xmlmsg1) - partPath3(xmlmsg1) - partPath4(xmlmsg1) - partPath5(xmlmsg1) - partPath6(xmlmsg1) -} - -func fullPath(xmldata [][]byte) { - for i, msg := range xmldata { - fmt.Println("\ndoc:", i) - fmt.Println(string(msg)) - // decode the XML - m, _ := mxj.NewMapXml(msg) - - // get the value for the key path of interest - path := "Envelope.Body.GetClaimStatusCodesResponse.GetClaimStatusCodesResult.ClaimStatusCodeRecord" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - continue - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - fmt.Println("values:", values, "\n") - for _, v := range values { - switch v.(type) { - case map[string]interface{}: - fmt.Println("map[string]interface{}:", v.(map[string]interface{})) - case []map[string]interface{}: - fmt.Println("[]map[string]interface{}:", v.([]map[string]interface{})) - case []interface{}: - fmt.Println("[]interface{}:", v.([]interface{})) - case interface{}: - fmt.Println("interface{}:", v.(interface{})) - } - } - } -} - -func partPath1(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "Envelope.Body.*.*.ClaimStatusCodeRecord" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} - -func partPath2(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "Envelope.Body.*.*.*" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} - -func partPath3(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "*.*.*.*.*" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} - -func partPath4(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "*.*.*.*.*.Description" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} - -func partPath5(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "*.*.*.*.*.*" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} - -func partPath6(msg []byte) { - fmt.Println("\nmsg:", string(msg)) - m, _ := mxj.NewMapXml(msg) - fmt.Println("m:", m.StringIndent()) - path := "*.*.*.*.*.*.*" - values, err := m.ValueForPath(path) - if err != nil { - fmt.Println("err:", err.Error()) - return - } - if values == nil { - fmt.Println("path:", path) - fmt.Println("No ClaimStatusCodesResult code records.") - return - } - fmt.Println("\nPath:", path) - fmt.Println("Number of code records:", len(values)) - for n, v := range values { - fmt.Printf("\t#%d: %v\n", n, v) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts3.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts3.go deleted file mode 100644 index 5bfe0628..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts3.go +++ /dev/null @@ -1,47 +0,0 @@ -// https://groups.google.com/forum/#!topic/golang-nuts/cok6xasvI3w -// retrieve 'src' values from 'image' tags - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" -) - -var xmldata = []byte(` - - - - - something else - - - - - - - -`) - -func main() { - fmt.Println("xmldata:", string(xmldata)) - - // get all image tag values - []interface{} - m, merr := mxj.NewMapXml(xmldata) - if merr != nil { - fmt.Println("merr:", merr.Error()) - return - } - - // grab all values for attribute "src" - // Note: attributes are prepended with a hyphen, '-'. - sources, err := m.ValuesForKey("-src") - if err != nil { - fmt.Println("err:", err.Error()) - return - } - - for _, src := range sources { - fmt.Println(src) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts4.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts4.go deleted file mode 100644 index 5ad4f9df..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts4.go +++ /dev/null @@ -1,50 +0,0 @@ -// https://groups.google.com/forum/#!topic/golang-nuts/-N9Toa6qlu8 -// shows that you can extract attribute values directly from tag/key path. -// NOTE: attribute values are encoded by prepending a hyphen, '-'. - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" -) - -var xmldata = []byte(` - - - - - - - - - - - - - - - - - - `) - -func main() { - fmt.Println("xmldata:", string(xmldata)) - - m, merr := mxj.NewMapXml(xmldata) - if merr != nil { - fmt.Println("merr:", merr) - return - } - - // Attributes are keys with prepended hyphen, '-'. - values, err := m.ValuesForPath("doc.some_tag.geoInfo.country.-name") - if err != nil { - fmt.Println("err:", err.Error()) - } - - for _, v := range values { - fmt.Println("v:", v) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5.go deleted file mode 100644 index a1b8d16a..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5.go +++ /dev/null @@ -1,75 +0,0 @@ -// gonuts5.go - from https://groups.google.com/forum/#!topic/golang-nuts/MWoYY19of3o -// problem is to extract entries from by "int name=" - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" -) - -var xmlData = []byte(` - - - - - - - 1 - - - - 1 - 2 - 3 - 4 - 5 - - - - - 1 - 2 - 3 - 4 - 5 - - - - -`) - -func main() { - // parse XML into a Map - m, merr := mxj.NewMapXml(xmlData) - if merr != nil { - fmt.Println("merr:", merr.Error()) - return - } - - // extract the 'list3-1-1-1' node - there'll be just 1? - // NOTE: attribute keys are prepended with '-' - lstVal, lerr := m.ValuesForPath("*.*.*.*.*", "-name:list3-1-1-1") - if lerr != nil { - fmt.Println("ierr:", lerr.Error()) - return - } - - // assuming just one value returned - create a new Map - mv := mxj.Map(lstVal[0].(map[string]interface{})) - - // extract the 'int' values by 'name' attribute: "-name" - // interate over list of 'name' values of interest - var names = []string{"field1", "field2", "field3", "field4", "field5"} - for _, n := range names { - vals, verr := mv.ValuesForKey("int", "-name:"+n) - if verr != nil { - fmt.Println("verr:", verr.Error(), len(vals)) - return - } - - // values for simple elements have key '#text' - // NOTE: there can be only one value for key '#text' - fmt.Println(n, ":", vals[0].(map[string]interface{})["#text"]) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5a.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5a.go deleted file mode 100644 index de60688f..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts5a.go +++ /dev/null @@ -1,75 +0,0 @@ -// gonuts5.go - from https://groups.google.com/forum/#!topic/golang-nuts/MWoYY19of3o -// problem is to extract entries from by "int name=" - -package main - -import ( - "fmt" - "github.com/clbanning/mxj" -) - -var xmlData = []byte(` - - - - - - - 1 - - - - 1 - 2 - 3 - 4 - 5 - - - - - 1 - 2 - 3 - 4 - 5 - - - - -`) - -func main() { - // parse XML into a Map - m, merr := mxj.NewMapXml(xmlData) - if merr != nil { - fmt.Println("merr:", merr.Error()) - return - } - - // extract the 'list3-1-1-1' node - there'll be just 1? - // NOTE: attribute keys are prepended with '-' - lstVal, lerr := m.ValuesForPath("*.*.*.*.*", "-name:list3-1-1-1") - if lerr != nil { - fmt.Println("ierr:", lerr.Error()) - return - } - - // assuming just one value returned - create a new Map - mv := mxj.Map(lstVal[0].(map[string]interface{})) - - // extract the 'int' values by 'name' attribute: "-name" - // interate over list of 'name' values of interest - var names = []string{"field1", "field2", "field3", "field4", "field5"} - for _, n := range names { - vals, verr := mv.ValuesForKey("*", "-name:"+n) - if verr != nil { - fmt.Println("verr:", verr.Error(), len(vals)) - return - } - - // values for simple elements have key '#text' - // NOTE: there can be only one value for key '#text' - fmt.Println(n, ":", vals[0].(map[string]interface{})["#text"]) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts6.go b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts6.go deleted file mode 100644 index 56b3d29e..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/gonuts6.go +++ /dev/null @@ -1,43 +0,0 @@ -/* https://groups.google.com/forum/#!topic/golang-nuts/EMXHB1nJoBA - -package main - -import "fmt" -import "encoding/json" - -func main() { - var v struct { - DBInstances []struct { - Endpoint struct { - Address string - } - } - } - json.Unmarshal(s, &v) - fmt.Println(v.DBInstances[0].Endpoint.Address) -} -*/ - -package main - -import "fmt" -import "github.com/clbanning/mxj" - -func main() { - m, err := mxj.NewMapJson(s) - if err != nil { - fmt.Println("err:", err.Error()) - } - v, err := m.ValuesForKey("Address") - // v, err := m.ValuesForPath("DBInstances[0].Endpoint.Address") - if err != nil { - fmt.Println("err:", err.Error()) - } - if len(v) > 0 { - fmt.Println(v[0].(string)) - } else { - fmt.Println("No value.") - } -} - -var s = []byte(`{ "DBInstances": [ { "PubliclyAccessible": true, "MasterUsername": "postgres", "LicenseModel": "postgresql-license", "VpcSecurityGroups": [ { "Status": "active", "VpcSecurityGroupId": "sg-e72a4282" } ], "InstanceCreateTime": "2014-06-29T03:52:59.268Z", "OptionGroupMemberships": [ { "Status": "in-sync", "OptionGroupName": "default:postgres-9-3" } ], "PendingModifiedValues": {}, "Engine": "postgres", "MultiAZ": true, "LatestRestorableTime": "2014-06-29T12:00:34Z", "DBSecurityGroups": [ { "Status": "active", "DBSecurityGroupName": "production-dbsecuritygroup-q4f0ugxpjck8" } ], "DBParameterGroups": [ { "DBParameterGroupName": "default.postgres9.3", "ParameterApplyStatus": "in-sync" } ], "AutoMinorVersionUpgrade": true, "PreferredBackupWindow": "06:59-07:29", "DBSubnetGroup": { "Subnets": [ { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-34e5d01c", "SubnetAvailabilityZone": { "Name": "us-east-1b", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-50759d27", "SubnetAvailabilityZone": { "Name": "us-east-1c", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-450a1f03", "SubnetAvailabilityZone": { "Name": "us-east-1d", "ProvisionedIopsCapable": false } } ], "DBSubnetGroupName": "default", "VpcId": "vpc-acb86cc9", "DBSubnetGroupDescription": "default", "SubnetGroupStatus": "Complete" }, "SecondaryAvailabilityZone": "us-east-1b", "ReadReplicaDBInstanceIdentifiers": [], "AllocatedStorage": 15, "BackupRetentionPeriod": 1, "DBName": "deis", "PreferredMaintenanceWindow": "fri:05:52-fri:06:22", "Endpoint": { "Port": 5432, "Address": "production.cfk8mskkbkeu.us-east-1.rds.amazonaws.com" }, "DBInstanceStatus": "available", "EngineVersion": "9.3.3", "AvailabilityZone": "us-east-1c", "DBInstanceClass": "db.m1.small", "DBInstanceIdentifier": "production" } ] }`) diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/metrics_data.zip b/Godeps/_workspace/src/github.com/clbanning/mxj/examples/metrics_data.zip deleted file mode 100644 index 38683749..00000000 Binary files a/Godeps/_workspace/src/github.com/clbanning/mxj/examples/metrics_data.zip and /dev/null differ diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/exists.go b/Godeps/_workspace/src/github.com/clbanning/mxj/exists.go deleted file mode 100644 index 25cff3c5..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/exists.go +++ /dev/null @@ -1,7 +0,0 @@ -package mxj - -// Checks whether the path exists -func (mv Map) Exists(path string) bool { - v, err := mv.ValuesForPath(path) - return err == nil && len(v) > 0 -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/exists_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/exists_test.go deleted file mode 100644 index f5ae7c4d..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/exists_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package mxj - -import "testing" - -func TestExists(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - }, - } - mv := Map(m) - - if !mv.Exists("Div.Colour") { - t.Fatal("Haven't found an existing element") - } - - if mv.Exists("Div.Color") { - t.Fatal("Have found a non existing element") - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files.go b/Godeps/_workspace/src/github.com/clbanning/mxj/files.go deleted file mode 100644 index 58971187..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files.go +++ /dev/null @@ -1,299 +0,0 @@ -package mxj - -import ( - "fmt" - "io" - "os" -) - -type Maps []Map - -func NewMaps() Maps { - return make(Maps, 0) -} - -type MapRaw struct { - M Map - R []byte -} - -// NewMapsFromXmlFile - creates an array from a file of JSON values. -func NewMapsFromJsonFile(name string) (Maps, error) { - fi, err := os.Stat(name) - if err != nil { - return nil, err - } - if !fi.Mode().IsRegular() { - return nil, fmt.Errorf("file %s is not a regular file", name) - } - - fh, err := os.Open(name) - if err != nil { - return nil, err - } - defer fh.Close() - - am := make([]Map, 0) - for { - m, raw, err := NewMapJsonReaderRaw(fh) - if err != nil && err != io.EOF { - return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(raw)) - } - if len(m) > 0 { - am = append(am, m) - } - if err == io.EOF { - break - } - } - return am, nil -} - -// ReadMapsFromJsonFileRaw - creates an array of MapRaw from a file of JSON values. -func NewMapsFromJsonFileRaw(name string) ([]MapRaw, error) { - fi, err := os.Stat(name) - if err != nil { - return nil, err - } - if !fi.Mode().IsRegular() { - return nil, fmt.Errorf("file %s is not a regular file", name) - } - - fh, err := os.Open(name) - if err != nil { - return nil, err - } - defer fh.Close() - - am := make([]MapRaw, 0) - for { - mr := new(MapRaw) - mr.M, mr.R, err = NewMapJsonReaderRaw(fh) - if err != nil && err != io.EOF { - return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(mr.R)) - } - if len(mr.M) > 0 { - am = append(am, *mr) - } - if err == io.EOF { - break - } - } - return am, nil -} - -// NewMapsFromXmlFile - creates an array from a file of XML values. -func NewMapsFromXmlFile(name string) (Maps, error) { - x := XmlWriterBufSize - XmlWriterBufSize = 0 - defer func() { - XmlWriterBufSize = x - }() - - fi, err := os.Stat(name) - if err != nil { - return nil, err - } - if !fi.Mode().IsRegular() { - return nil, fmt.Errorf("file %s is not a regular file", name) - } - - fh, err := os.Open(name) - if err != nil { - return nil, err - } - defer fh.Close() - - am := make([]Map, 0) - for { - m, raw, err := NewMapXmlReaderRaw(fh) - if err != nil && err != io.EOF { - return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(raw)) - } - if len(m) > 0 { - am = append(am, m) - } - if err == io.EOF { - break - } - } - return am, nil -} - -// NewMapsFromXmlFileRaw - creates an array of MapRaw from a file of XML values. -// NOTE: the slice with the raw XML is clean with no extra capacity - unlike NewMapXmlReaderRaw(). -// It is slow at parsing a file from disk and is intended for relatively small utility files. -func NewMapsFromXmlFileRaw(name string) ([]MapRaw, error) { - x := XmlWriterBufSize - XmlWriterBufSize = 0 - defer func() { - XmlWriterBufSize = x - }() - - fi, err := os.Stat(name) - if err != nil { - return nil, err - } - if !fi.Mode().IsRegular() { - return nil, fmt.Errorf("file %s is not a regular file", name) - } - - fh, err := os.Open(name) - if err != nil { - return nil, err - } - defer fh.Close() - - am := make([]MapRaw, 0) - for { - mr := new(MapRaw) - mr.M, mr.R, err = NewMapXmlReaderRaw(fh) - if err != nil && err != io.EOF { - return am, fmt.Errorf("error: %s - reading: %s", err.Error(), string(mr.R)) - } - if len(mr.M) > 0 { - am = append(am, *mr) - } - if err == io.EOF { - break - } - } - return am, nil -} - -// ------------------------ Maps writing ------------------------- -// These are handy-dandy methods for dumping configuration data, etc. - -// JsonString - analogous to mv.Json() -func (mvs Maps) JsonString(safeEncoding ...bool) (string, error) { - var s string - for _, v := range mvs { - j, err := v.Json() - if err != nil { - return s, err - } - s += string(j) - } - return s, nil -} - -// JsonStringIndent - analogous to mv.JsonIndent() -func (mvs Maps) JsonStringIndent(prefix, indent string, safeEncoding ...bool) (string, error) { - var s string - var haveFirst bool - for _, v := range mvs { - j, err := v.JsonIndent(prefix, indent) - if err != nil { - return s, err - } - if haveFirst { - s += "\n" - } else { - haveFirst = true - } - s += string(j) - } - return s, nil -} - -// XmlString - analogous to mv.Xml() -func (mvs Maps) XmlString() (string, error) { - var s string - for _, v := range mvs { - x, err := v.Xml() - if err != nil { - return s, err - } - s += string(x) - } - return s, nil -} - -// XmlStringIndent - analogous to mv.XmlIndent() -func (mvs Maps) XmlStringIndent(prefix, indent string) (string, error) { - var s string - for _, v := range mvs { - x, err := v.XmlIndent(prefix, indent) - if err != nil { - return s, err - } - s += string(x) - } - return s, nil -} - -// JsonFile - write Maps to named file as JSON -// Note: the file will be created, if necessary; if it exists it will be truncated. -// If you need to append to a file, open it and use JsonWriter method. -func (mvs Maps) JsonFile(file string, safeEncoding ...bool) error { - var encoding bool - if len(safeEncoding) == 1 { - encoding = safeEncoding[0] - } - s, err := mvs.JsonString(encoding) - if err != nil { - return err - } - fh, err := os.Create(file) - if err != nil { - return err - } - defer fh.Close() - fh.WriteString(s) - return nil -} - -// JsonFileIndent - write Maps to named file as pretty JSON -// Note: the file will be created, if necessary; if it exists it will be truncated. -// If you need to append to a file, open it and use JsonIndentWriter method. -func (mvs Maps) JsonFileIndent(file, prefix, indent string, safeEncoding ...bool) error { - var encoding bool - if len(safeEncoding) == 1 { - encoding = safeEncoding[0] - } - s, err := mvs.JsonStringIndent(prefix, indent, encoding) - if err != nil { - return err - } - fh, err := os.Create(file) - if err != nil { - return err - } - defer fh.Close() - fh.WriteString(s) - return nil -} - -// XmlFile - write Maps to named file as XML -// Note: the file will be created, if necessary; if it exists it will be truncated. -// If you need to append to a file, open it and use XmlWriter method. -func (mvs Maps) XmlFile(file string) error { - s, err := mvs.XmlString() - if err != nil { - return err - } - fh, err := os.Create(file) - if err != nil { - return err - } - defer fh.Close() - fh.WriteString(s) - return nil -} - -// XmlFileIndent - write Maps to named file as pretty XML -// Note: the file will be created,if necessary; if it exists it will be truncated. -// If you need to append to a file, open it and use XmlIndentWriter method. -func (mvs Maps) XmlFileIndent(file, prefix, indent string) error { - s, err := mvs.XmlStringIndent(prefix, indent) - if err != nil { - return err - } - fh, err := os.Create(file) - if err != nil { - return err - } - defer fh.Close() - fh.WriteString(s) - return nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badjson b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badjson deleted file mode 100644 index d1872004..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badjson +++ /dev/null @@ -1,2 +0,0 @@ -{ "this":"is", "a":"test", "file":"for", "files_test.go":"case" } -{ "with":"some", "bad":JSON, "in":"it" } diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badxml b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badxml deleted file mode 100644 index 4736ef97..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.badxml +++ /dev/null @@ -1,9 +0,0 @@ - - test - for files.go - - - some - doc - test case - diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.go deleted file mode 100644 index 52778aef..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.go +++ /dev/null @@ -1,168 +0,0 @@ -package mxj - -import ( - "fmt" - "testing" -) - -func TestFilesHeader(t *testing.T) { - fmt.Println("\n---------------- files_test.go ...\n") -} - -func TestNewJsonFile(t *testing.T) { - fmt.Println("NewMapsFromJsonFile()") - am, err := NewMapsFromJsonFile("files_test.json") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range am { - fmt.Printf("%v\n", v) - } - - am, err = NewMapsFromJsonFile("nil") - if err == nil { - t.Fatal("no error returned for read of nil file") - } - fmt.Println("caught error: ", err.Error()) - - am, err = NewMapsFromJsonFile("files_test.badjson") - if err == nil { - t.Fatal("no error returned for read of badjson file") - } - fmt.Println("caught error: ", err.Error()) -} - -func TestNewJsonFileRaw(t *testing.T) { - fmt.Println("NewMapsFromJsonFileRaw()") - mr, err := NewMapsFromJsonFileRaw("files_test.json") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range mr { - fmt.Printf("%v\n", v) - } - - mr, err = NewMapsFromJsonFileRaw("nil") - if err == nil { - t.Fatal("no error returned for read of nil file") - } - fmt.Println("caught error: ", err.Error()) - - mr, err = NewMapsFromJsonFileRaw("files_test.badjson") - if err == nil { - t.Fatal("no error returned for read of badjson file") - } - fmt.Println("caught error: ", err.Error()) -} - -func TestNewXmFile(t *testing.T) { - fmt.Println("NewMapsFromXmlFile()") - am, err := NewMapsFromXmlFile("files_test.xml") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range am { - fmt.Printf("%v\n", v) - } - - am, err = NewMapsFromXmlFile("nil") - if err == nil { - t.Fatal("no error returned for read of nil file") - } - fmt.Println("caught error: ", err.Error()) - - am, err = NewMapsFromXmlFile("files_test.badxml") - if err == nil { - t.Fatal("no error returned for read of badjson file") - } - fmt.Println("caught error: ", err.Error()) -} - -func TestNewXmFileRaw(t *testing.T) { - fmt.Println("NewMapsFromXmlFileRaw()") - mr, err := NewMapsFromXmlFileRaw("files_test.xml") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range mr { - fmt.Printf("%v\n", v) - } - - mr, err = NewMapsFromXmlFileRaw("nil") - if err == nil { - t.Fatal("no error returned for read of nil file") - } - fmt.Println("caught error: ", err.Error()) - - mr, err = NewMapsFromXmlFileRaw("files_test.badxml") - if err == nil { - t.Fatal("no error returned for read of badjson file") - } - fmt.Println("caught error: ", err.Error()) -} - -func TestMaps(t *testing.T) { - fmt.Println("TestMaps()") - mvs := NewMaps() - for i := 0; i < 2; i++ { - m, _ := NewMapJson([]byte(`{ "this":"is", "a":"test" }`)) - mvs = append(mvs, m) - } - fmt.Println("mvs:", mvs) - - s, _ := mvs.JsonString() - fmt.Println("JsonString():", s) - - s, _ = mvs.JsonStringIndent("", " ") - fmt.Println("JsonStringIndent():", s) - - s, _ = mvs.XmlString() - fmt.Println("XmlString():", s) - - s, _ = mvs.XmlStringIndent("", " ") - fmt.Println("XmlStringIndent():", s) -} - -func TestJsonFile(t *testing.T) { - am, err := NewMapsFromJsonFile("files_test.json") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range am { - fmt.Printf("%v\n", v) - } - - err = am.JsonFile("files_test_dup.json") - if err != nil { - t.Fatal(err.Error()) - } - fmt.Println("files_test_dup.json written") - - err = am.JsonFileIndent("files_test_indent.json", "", " ") - if err != nil { - t.Fatal(err.Error()) - } - fmt.Println("files_test_indent.json written") -} - -func TestXmlFile(t *testing.T) { - am, err := NewMapsFromXmlFile("files_test.xml") - if err != nil { - t.Fatal(err.Error()) - } - for _, v := range am { - fmt.Printf("%v\n", v) - } - - err = am.XmlFile("files_test_dup.xml") - if err != nil { - t.Fatal(err.Error()) - } - fmt.Println("files_test_dup.xml written") - - err = am.XmlFileIndent("files_test_indent.xml", "", " ") - if err != nil { - t.Fatal(err.Error()) - } - fmt.Println("files_test_indent.xml written") -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.json b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.json deleted file mode 100644 index e9a3ddf4..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.json +++ /dev/null @@ -1,2 +0,0 @@ -{ "this":"is", "a":"test", "file":"for", "files_test.go":"case" } -{ "with":"just", "two":2, "JSON":"values", "true":true } diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.xml b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.xml deleted file mode 100644 index 65cf021f..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test.xml +++ /dev/null @@ -1,9 +0,0 @@ - - test - for files.go - - - some - doc - test case - diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.json b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.json deleted file mode 100644 index 2becb6a4..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.json +++ /dev/null @@ -1 +0,0 @@ -{"a":"test","file":"for","files_test.go":"case","this":"is"}{"JSON":"values","true":true,"two":2,"with":"just"} \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.xml b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.xml deleted file mode 100644 index aa63dda7..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_dup.xml +++ /dev/null @@ -1 +0,0 @@ -testfor files.gosomedoctest case \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.json b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.json deleted file mode 100644 index 6fde1563..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "a": "test", - "file": "for", - "files_test.go": "case", - "this": "is" -} -{ - "JSON": "values", - "true": true, - "two": 2, - "with": "just" -} \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.xml b/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.xml deleted file mode 100644 index febee213..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/files_test_indent.xml +++ /dev/null @@ -1,8 +0,0 @@ - - test - for files.go - - some - doc - test case - \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x.go b/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x.go deleted file mode 100644 index 868c55a5..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// j2x.go - For (mostly) backwards compatibility with legacy j2x package. -// Wrappers for end-to-end JSON to XML transformation and value manipulation. -package j2x - -import ( - . "github.com/clbanning/mxj" - "io" -) - -// FromJson() --> map[string]interface{} -func JsonToMap(jsonVal []byte) (map[string]interface{}, error) { - return NewMapJson(jsonVal) -} - -// interface{} --> ToJson (w/o safe encoding, default) { -func MapToJson(m map[string]interface{}, safeEncoding ...bool) ([]byte, error) { - return Map(m).Json() -} - -// FromJson() --> ToXml(). -func JsonToXml(jsonVal []byte) ([]byte, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.Xml() -} - -// FromJson() --> ToXmlWriter(). -func JsonToXmlWriter(jsonVal []byte, xmlWriter io.Writer) ([]byte, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.XmlWriterRaw(xmlWriter) -} - -// FromJsonReader() --> ToXml(). -func JsonReaderToXml(jsonReader io.Reader) ([]byte, []byte, error) { - m, jraw, err := NewMapJsonReaderRaw(jsonReader) - if err != nil { - return jraw, nil, err - } - x, xerr := m.Xml() - return jraw, x, xerr -} - -// FromJsonReader() --> ToXmlWriter(). Handy for transforming bulk message sets. -func JsonReaderToXmlWriter(jsonReader io.Reader, xmlWriter io.Writer) ([]byte, []byte, error) { - m, jraw, err := NewMapJsonReaderRaw(jsonReader) - if err != nil { - return jraw, nil, err - } - xraw, xerr := m.XmlWriterRaw(xmlWriter) - return jraw, xraw, xerr -} - -// JSON wrappers for Map methods implementing key path and value functions. - -// Wrap PathsForKey for JSON. -func JsonPathsForKey(jsonVal []byte, key string) ([]string, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - paths := m.PathsForKey(key) - return paths, nil -} - -// Wrap PathForKeyShortest for JSON. -func JsonPathForKeyShortest(jsonVal []byte, key string) (string, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return "", err - } - path := m.PathForKeyShortest(key) - return path, nil -} - -// Wrap ValuesForKey for JSON. -func JsonValuesForKey(jsonVal []byte, key string, subkeys ...string) ([]interface{}, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.ValuesForKey(key, subkeys...) -} - -// Wrap ValuesForKeyPath for JSON. -func JsonValuesForKeyPath(jsonVal []byte, path string, subkeys ...string) ([]interface{}, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.ValuesForPath(path, subkeys...) -} - -// Wrap UpdateValuesForPath for JSON -// 'jsonVal' is XML value -// 'newKeyValue' is the value to replace an existing value at the end of 'path' -// 'path' is the dot-notation path with the key whose value is to be replaced at the end -// (can include wildcard character, '*') -// 'subkeys' are key:value pairs of key:values that must match for the key -func JsonUpdateValsForPath(jsonVal []byte, newKeyValue interface{}, path string, subkeys ...string) ([]byte, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - _, err = m.UpdateValuesForPath(newKeyValue, path, subkeys...) - if err != nil { - return nil, err - } - return m.Json() -} - -// Wrap NewMap for JSON and return as JSON -// 'jsonVal' is an JSON value -// 'keypairs' are "oldKey:newKey" values that conform to 'keypairs' in (Map)NewMap. -func JsonNewJson(jsonVal []byte, keypairs ...string) ([]byte, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - n, err := m.NewMap(keypairs...) - if err != nil { - return nil, err - } - return n.Json() -} - -// Wrap NewMap for JSON and return as XML -// 'jsonVal' is an JSON value -// 'keypairs' are "oldKey:newKey" values that conform to 'keypairs' in (Map)NewMap. -func JsonNewXml(jsonVal []byte, keypairs ...string) ([]byte, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - n, err := m.NewMap(keypairs...) - if err != nil { - return nil, err - } - return n.Xml() -} - -// Wrap LeafNodes for JSON. -// 'jsonVal' is an JSON value -func JsonLeafNodes(jsonVal []byte) ([]LeafNode, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.LeafNodes(), nil -} - -// Wrap LeafValues for JSON. -// 'jsonVal' is an JSON value -func JsonLeafValues(jsonVal []byte) ([]interface{}, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.LeafValues(), nil -} - -// Wrap LeafPath for JSON. -// 'xmlVal' is an JSON value -func JsonLeafPath(jsonVal []byte) ([]string, error) { - m, err := NewMapJson(jsonVal) - if err != nil { - return nil, err - } - return m.LeafPaths(), nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x_test.go deleted file mode 100644 index 4a25605c..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x/j2x_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// thanks to Chris Malek (chris.r.malek@gmail.com) for suggestion to handle JSON list docs. - -package j2x - -import ( - "bytes" - "fmt" - "io/ioutil" - "testing" -) - -func TestJsonToXml_1(t *testing.T) { - // mimic a io.Reader - // Body := bytes.NewReader([]byte(`{"some-null-value":"", "a-non-null-value":"bar"}`)) - Body := bytes.NewReader([]byte(`[{"some-null-value":"", "a-non-null-value":"bar"}]`)) - - //body, err := ioutil.ReadAll(req.Body) - body, err := ioutil.ReadAll(Body) - if err != nil { - t.Fatal(err) - } - fmt.Println(string(body)) - //if err != nil { - // t.Fatal(err) - //} - - var xmloutput []byte - //xmloutput, err = j2x.JsonToXml(body) - xmloutput, err = JsonToXml(body) - - //log.Println(string(xmloutput)) - - if err != nil { - t.Fatal(err) - // log.Println(err) - // http.Error(rw, "Could not convert to xml", 400) - } - fmt.Println("xmloutput:", string(xmloutput)) -} - -func TestJsonToXml_2(t *testing.T) { - // mimic a io.Reader - Body := bytes.NewReader([]byte(`{"somekey":[{"value":"1st"},{"value":"2nd"}]}`)) - - //body, err := ioutil.ReadAll(req.Body) - body, err := ioutil.ReadAll(Body) - if err != nil { - t.Fatal(err) - } - fmt.Println(string(body)) - //if err != nil { - // t.Fatal(err) - //} - - var xmloutput []byte - //xmloutput, err = j2x.JsonToXml(body) - xmloutput, err = JsonToXml(body) - - //log.Println(string(xmloutput)) - - if err != nil { - t.Fatal(err) - // log.Println(err) - // http.Error(rw, "Could not convert to xml", 400) - } - fmt.Println("xmloutput:", string(xmloutput)) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/j2x_test.go deleted file mode 100644 index b88a64d5..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/j2x_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package mxj - -import ( - "fmt" - "testing" -) - -var jjdata = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&", "key5":null }`) - -func TestJ2XHeader(t *testing.T) { - fmt.Println("\n---------------- j2x_test .go ...\n") -} - -func TestJ2X(t *testing.T) { - - m, err := NewMapJson(jjdata) - if err != nil { - t.Fatal("NewMapJson, err:", err) - } - - x, err := m.Xml() - if err != nil { - t.Fatal("m.Xml(), err:", err) - } - - fmt.Println("j2x, jdata:", string(jjdata)) - fmt.Println("j2x, m :", m) - fmt.Println("j2x, xml :", string(x)) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/json.go b/Godeps/_workspace/src/github.com/clbanning/mxj/json.go deleted file mode 100644 index 34c1c0b3..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/json.go +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -package mxj - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "time" -) - -// ------------------------------ write JSON ----------------------- - -// Just a wrapper on json.Marshal. -// If option safeEncoding is'true' then safe encoding of '<', '>' and '&' -// is preserved. (see encoding/json#Marshal, encoding/json#Encode) -func (mv Map) Json(safeEncoding ...bool) ([]byte, error) { - var s bool - if len(safeEncoding) == 1 { - s = safeEncoding[0] - } - - b, err := json.Marshal(mv) - - if !s { - b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1) - b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1) - b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1) - } - return b, err -} - -// Just a wrapper on json.MarshalIndent. -// If option safeEncoding is'true' then safe encoding of '<' , '>' and '&' -// is preserved. (see encoding/json#Marshal, encoding/json#Encode) -func (mv Map) JsonIndent(prefix, indent string, safeEncoding ...bool) ([]byte, error) { - var s bool - if len(safeEncoding) == 1 { - s = safeEncoding[0] - } - - b, err := json.MarshalIndent(mv, prefix, indent) - if !s { - b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1) - b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1) - b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1) - } - return b, err -} - -// The following implementation is provided for symmetry with NewMapJsonReader[Raw] -// The names will also provide a key for the number of return arguments. - -// Writes the Map as JSON on the Writer. -// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved. -func (mv Map) JsonWriter(jsonWriter io.Writer, safeEncoding ...bool) error { - b, err := mv.Json(safeEncoding...) - if err != nil { - return err - } - - _, err = jsonWriter.Write(b) - return err -} - -// Writes the Map as JSON on the Writer. []byte is the raw JSON that was written. -// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved. -func (mv Map) JsonWriterRaw(jsonWriter io.Writer, safeEncoding ...bool) ([]byte, error) { - b, err := mv.Json(safeEncoding...) - if err != nil { - return b, err - } - - _, err = jsonWriter.Write(b) - return b, err -} - -// Writes the Map as pretty JSON on the Writer. -// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved. -func (mv Map) JsonIndentWriter(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) error { - b, err := mv.JsonIndent(prefix, indent, safeEncoding...) - if err != nil { - return err - } - - _, err = jsonWriter.Write(b) - return err -} - -// Writes the Map as pretty JSON on the Writer. []byte is the raw JSON that was written. -// If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved. -func (mv Map) JsonIndentWriterRaw(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) ([]byte, error) { - b, err := mv.JsonIndent(prefix, indent, safeEncoding...) - if err != nil { - return b, err - } - - _, err = jsonWriter.Write(b) - return b, err -} - -// --------------------------- read JSON ----------------------------- - -// Parse numeric values as json.Number types - see encoding/json#Number -var JsonUseNumber bool - -// Just a wrapper on json.Unmarshal -// Converting JSON to XML is a simple as: -// ... -// mapVal, merr := mxj.NewMapJson(jsonVal) -// if merr != nil { -// // handle error -// } -// xmlVal, xerr := mapVal.Xml() -// if xerr != nil { -// // handle error -// } -// NOTE: as a special case, passing a list, e.g., [{"some-null-value":"", "a-non-null-value":"bar"}], -// will be interpreted as having the root key 'object' prepended - {"object":[ ... ]} - to unmarshal to a Map. -// See mxj/j2x/j2x_test.go. -func NewMapJson(jsonVal []byte) (Map, error) { - // empty or nil begets empty - if len(jsonVal) == 0 { - m := make(map[string]interface{}, 0) - return m, nil - } - // handle a goofy case ... - if jsonVal[0] == '[' { - jsonVal = []byte(`{"object":` + string(jsonVal) + `}`) - } - m := make(map[string]interface{}) - // err := json.Unmarshal(jsonVal, &m) - buf := bytes.NewReader(jsonVal) - dec := json.NewDecoder(buf) - if JsonUseNumber { - dec.UseNumber() - } - err := dec.Decode(&m) - return m, err -} - -// Retrieve a Map value from an io.Reader. -// NOTE: The raw JSON off the reader is buffered to []byte using a ByteReader. If the io.Reader is an -// os.File, there may be significant performance impact. If the io.Reader is wrapping a []byte -// value in-memory, however, such as http.Request.Body you CAN use it to efficiently unmarshal -// a JSON object. -func NewMapJsonReader(jsonReader io.Reader) (Map, error) { - jb, err := getJson(jsonReader) - if err != nil || len(*jb) == 0 { - return nil, err - } - - // Unmarshal the 'presumed' JSON string - return NewMapJson(*jb) -} - -// Retrieve a Map value and raw JSON - []byte - from an io.Reader. -// NOTE: The raw JSON off the reader is buffered to []byte using a ByteReader. If the io.Reader is an -// os.File, there may be significant performance impact. If the io.Reader is wrapping a []byte -// value in-memory, however, such as http.Request.Body you CAN use it to efficiently unmarshal -// a JSON object and retrieve the raw JSON in a single call. -func NewMapJsonReaderRaw(jsonReader io.Reader) (Map, []byte, error) { - jb, err := getJson(jsonReader) - if err != nil || len(*jb) == 0 { - return nil, *jb, err - } - - // Unmarshal the 'presumed' JSON string - m, merr := NewMapJson(*jb) - return m, *jb, merr -} - -// Pull the next JSON string off the stream: just read from first '{' to its closing '}'. -// Returning a pointer to the slice saves 16 bytes - maybe unnecessary, but internal to package. -func getJson(rdr io.Reader) (*[]byte, error) { - bval := make([]byte, 1) - jb := make([]byte, 0) - var inQuote, inJson bool - var parenCnt int - var previous byte - - // scan the input for a matched set of {...} - // json.Unmarshal will handle syntax checking. - for { - _, err := rdr.Read(bval) - if err != nil { - if err == io.EOF && inJson && parenCnt > 0 { - return &jb, fmt.Errorf("no closing } for JSON string: %s", string(jb)) - } - return &jb, err - } - switch bval[0] { - case '{': - if !inQuote { - parenCnt++ - inJson = true - } - case '}': - if !inQuote { - parenCnt-- - } - if parenCnt < 0 { - return nil, fmt.Errorf("closing } without opening {: %s", string(jb)) - } - case '"': - if inQuote { - if previous == '\\' { - break - } - inQuote = false - } else { - inQuote = true - } - case '\n', '\r', '\t', ' ': - if !inQuote { - continue - } - } - if inJson { - jb = append(jb, bval[0]) - if parenCnt == 0 { - break - } - } - previous = bval[0] - } - - return &jb, nil -} - -// ------------------------------- JSON Reader handler via Map values ----------------------- - -// Default poll delay to keep Handler from spinning on an open stream -// like sitting on os.Stdin waiting for imput. -var jhandlerPollInterval = time.Duration(1e6) - -// While unnecessary, we make HandleJsonReader() have the same signature as HandleXmlReader(). -// This avoids treating one or other as a special case and discussing the underlying stdlib logic. - -// Bulk process JSON using handlers that process a Map value. -// 'rdr' is an io.Reader for the JSON (stream). -// 'mapHandler' is the Map processing handler. Return of 'false' stops io.Reader processing. -// 'errHandler' is the error processor. Return of 'false' stops io.Reader processing and returns the error. -// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized. -// This means that you can stop reading the file on error or after processing a particular message. -// To have reading and handling run concurrently, pass argument to a go routine in handler and return 'true'. -func HandleJsonReader(jsonReader io.Reader, mapHandler func(Map) bool, errHandler func(error) bool) error { - var n int - for { - m, merr := NewMapJsonReader(jsonReader) - n++ - - // handle error condition with errhandler - if merr != nil && merr != io.EOF { - merr = fmt.Errorf("[jsonReader: %d] %s", n, merr.Error()) - if ok := errHandler(merr); !ok { - // caused reader termination - return merr - } - continue - } - - // pass to maphandler - if len(m) != 0 { - if ok := mapHandler(m); !ok { - break - } - } else if merr != io.EOF { - <-time.After(jhandlerPollInterval) - } - - if merr == io.EOF { - break - } - } - return nil -} - -// Bulk process JSON using handlers that process a Map value and the raw JSON. -// 'rdr' is an io.Reader for the JSON (stream). -// 'mapHandler' is the Map and raw JSON - []byte - processor. Return of 'false' stops io.Reader processing. -// 'errHandler' is the error and raw JSON processor. Return of 'false' stops io.Reader processing and returns the error. -// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized. -// This means that you can stop reading the file on error or after processing a particular message. -// To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return 'true'. -func HandleJsonReaderRaw(jsonReader io.Reader, mapHandler func(Map, []byte) bool, errHandler func(error, []byte) bool) error { - var n int - for { - m, raw, merr := NewMapJsonReaderRaw(jsonReader) - n++ - - // handle error condition with errhandler - if merr != nil && merr != io.EOF { - merr = fmt.Errorf("[jsonReader: %d] %s", n, merr.Error()) - if ok := errHandler(merr, raw); !ok { - // caused reader termination - return merr - } - continue - } - - // pass to maphandler - if len(m) != 0 { - if ok := mapHandler(m, raw); !ok { - break - } - } else if merr != io.EOF { - <-time.After(jhandlerPollInterval) - } - - if merr == io.EOF { - break - } - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/json_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/json_test.go deleted file mode 100644 index 7c97d2f7..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/json_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package mxj - -import ( - "bytes" - "fmt" - "io" - "testing" -) - -var jdata = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&", "key5":null }`) -var jdata2 = []byte(`{ "key1":"string", "key2":34, "key3":true, "key4":"unsafe: <>&" }, - { "key":"value in new JSON string" }`) - -func TestJsonHeader(t *testing.T) { - fmt.Println("\n---------------- json_test.go ...\n") -} - -func TestNewMapJson(t *testing.T) { - - m, merr := NewMapJson(jdata) - if merr != nil { - t.Fatal("NewMapJson, merr:", merr.Error()) - } - - fmt.Println("NewMapJson, jdata:", string(jdata)) - fmt.Printf("NewMapJson, m : %#v\n", m) -} - -func TestNewMapJsonNumber(t *testing.T) { - - JsonUseNumber = true - - m, merr := NewMapJson(jdata) - if merr != nil { - t.Fatal("NewMapJson, merr:", merr.Error()) - } - - fmt.Println("NewMapJson, jdata:", string(jdata)) - fmt.Printf("NewMapJson, m : %#v\n", m) - - JsonUseNumber = false -} - -func TestNewMapJsonError(t *testing.T) { - - m, merr := NewMapJson(jdata[:len(jdata)-2]) - if merr == nil { - t.Fatal("NewMapJsonError, m:", m) - } - - fmt.Println("NewMapJsonError, jdata :", string(jdata[:len(jdata)-2])) - fmt.Println("NewMapJsonError, merror:", merr.Error()) - - newData := []byte(`{ "this":"is", "in":error }`) - m, merr = NewMapJson(newData) - if merr == nil { - t.Fatal("NewMapJsonError, m:", m) - } - - fmt.Println("NewMapJsonError, newData :", string(newData)) - fmt.Println("NewMapJsonError, merror :", merr.Error()) -} - -func TestNewMapJsonReader(t *testing.T) { - - rdr := bytes.NewBuffer(jdata2) - - for { - m, jb, merr := NewMapJsonReaderRaw(rdr) - if merr != nil && merr != io.EOF { - t.Fatal("NewMapJsonReader, merr:", merr.Error()) - } - if merr == io.EOF { - break - } - - fmt.Println("NewMapJsonReader, jb:", string(jb)) - fmt.Printf("NewMapJsonReader, m : %#v\n", m) - } -} - -func TestNewMapJsonReaderNumber(t *testing.T) { - - JsonUseNumber = true - - rdr := bytes.NewBuffer(jdata2) - - for { - m, jb, merr := NewMapJsonReaderRaw(rdr) - if merr != nil && merr != io.EOF { - t.Fatal("NewMapJsonReader, merr:", merr.Error()) - } - if merr == io.EOF { - break - } - - fmt.Println("NewMapJsonReader, jb:", string(jb)) - fmt.Printf("NewMapJsonReader, m : %#v\n", m) - } - - JsonUseNumber = false -} - -func TestJson(t *testing.T) { - - m, _ := NewMapJson(jdata) - - j, jerr := m.Json() - if jerr != nil { - t.Fatal("Json, jerr:", jerr.Error()) - } - - fmt.Println("Json, jdata:", string(jdata)) - fmt.Println("Json, j :", string(j)) - - j, _ = m.Json(true) - fmt.Println("Json, j safe:", string(j)) -} - -func TestJsonWriter(t *testing.T) { - mv := Map(map[string]interface{}{"this": "is a", "float": 3.14159, "and": "a", "bool": true}) - - w := new(bytes.Buffer) - raw, err := mv.JsonWriterRaw(w) - if err != nil { - t.Fatal("err:", err.Error()) - } - - b := make([]byte, w.Len()) - _, err = w.Read(b) - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("JsonWriter, raw:", string(raw)) - fmt.Println("JsonWriter, b :", string(b)) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues.go b/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues.go deleted file mode 100644 index 7feb766b..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues.go +++ /dev/null @@ -1,658 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// keyvalues.go: Extract values from an arbitrary XML doc. Tag path can include wildcard characters. - -package mxj - -import ( - "errors" - "fmt" - "strconv" - "strings" -) - -// ----------------------------- get everything FOR a single key ------------------------- - -const ( - minArraySize = 32 -) - -var defaultArraySize int = minArraySize - -// Adjust the buffers for expected number of values to return from ValuesForKey() and ValuesForPath(). -// This can have the effect of significantly reducing memory allocation-copy functions for large data sets. -// Returns the initial buffer size. -func SetArraySize(size int) int { - if size > minArraySize { - defaultArraySize = size - } else { - defaultArraySize = minArraySize - } - return defaultArraySize -} - -// Return all values in Map, 'mv', associated with a 'key'. If len(returned_values) == 0, then no match. -// On error, the returned array is 'nil'. NOTE: 'key' can be wildcard, "*". -// 'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list. -// - By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them. -// - For attributes prefix the label with a hyphen, '-', e.g., "-seq:3". -// - If the 'key' refers to a list, then "key:value" could select a list member of the list. -// - The subkey can be wildcarded - "key:*" - to require that it's there with some value. -// - If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an -// exclusion critera - e.g., "!author:William T. Gaddis". -func (mv Map) ValuesForKey(key string, subkeys ...string) ([]interface{}, error) { - m := map[string]interface{}(mv) - var subKeyMap map[string]interface{} - if len(subkeys) > 0 { - var err error - subKeyMap, err = getSubKeyMap(subkeys...) - if err != nil { - return nil, err - } - } - - ret := make([]interface{}, 0, defaultArraySize) - var cnt int - hasKey(m, key, &ret, &cnt, subKeyMap) - return ret[:cnt], nil - // ret := make([]interface{}, 0) - // hasKey(m, key, &ret, subKeyMap) - // return ret, nil -} - -// hasKey - if the map 'key' exists append it to array -// if it doesn't do nothing except scan array and map values -func hasKey(iv interface{}, key string, ret *[]interface{}, cnt *int, subkeys map[string]interface{}) { - // func hasKey(iv interface{}, key string, ret *[]interface{}, subkeys map[string]interface{}) { - switch iv.(type) { - case map[string]interface{}: - vv := iv.(map[string]interface{}) - // see if the current value is of interest - if v, ok := vv[key]; ok { - switch v.(type) { - case map[string]interface{}: - if hasSubKeys(v, subkeys) { - *ret = append(*ret, v) - *cnt++ - } - case []interface{}: - for _, av := range v.([]interface{}) { - if hasSubKeys(av, subkeys) { - *ret = append(*ret, av) - *cnt++ - } - } - default: - if len(subkeys) == 0 { - *ret = append(*ret, v) - *cnt++ - } - } - } - - // wildcard case - if key == "*" { - for _, v := range vv { - switch v.(type) { - case map[string]interface{}: - if hasSubKeys(v, subkeys) { - *ret = append(*ret, v) - *cnt++ - } - case []interface{}: - for _, av := range v.([]interface{}) { - if hasSubKeys(av, subkeys) { - *ret = append(*ret, av) - *cnt++ - } - } - default: - if len(subkeys) == 0 { - *ret = append(*ret, v) - *cnt++ - } - } - } - } - - // scan the rest - for _, v := range vv { - hasKey(v, key, ret, cnt, subkeys) - // hasKey(v, key, ret, subkeys) - } - case []interface{}: - for _, v := range iv.([]interface{}) { - hasKey(v, key, ret, cnt, subkeys) - // hasKey(v, key, ret, subkeys) - } - } -} - -// ----------------------- get everything for a node in the Map --------------------------- - -// Allow indexed arrays in "path" specification. (Request from Abhijit Kadam - abhijitk100@gmail.com.) -// 2014.04.28 - implementation note. -// Implemented as a wrapper of (old)ValuesForPath() because we need look-ahead logic to handle expansion -// of wildcards and unindexed arrays. Embedding such logic into valuesForKeyPath() would have made the -// code much more complicated; this wrapper is straightforward, easy to debug, and doesn't add significant overhead. - -// Retrieve all values for a path from the Map. If len(returned_values) == 0, then no match. -// On error, the returned array is 'nil'. -// 'path' is a dot-separated path of key values. -// - If a node in the path is '*', then everything beyond is walked. -// - 'path' can contain indexed array references, such as, "*.data[1]" and "msgs[2].data[0].field" - -// even "*[2].*[0].field". -// 'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list. -// - By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them. -// - For attributes prefix the label with a hyphen, '-', e.g., "-seq:3". -// - If the 'path' refers to a list, then "tag:value" would return member of the list. -// - The subkey can be wildcarded - "key:*" - to require that it's there with some value. -// - If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an -// exclusion critera - e.g., "!author:William T. Gaddis". -func (mv Map) ValuesForPath(path string, subkeys ...string) ([]interface{}, error) { - // If there are no array indexes in path, use legacy ValuesForPath() logic. - if strings.Index(path, "[") < 0 { - return mv.oldValuesForPath(path, subkeys...) - } - - var subKeyMap map[string]interface{} - if len(subkeys) > 0 { - var err error - subKeyMap, err = getSubKeyMap(subkeys...) - if err != nil { - return nil, err - } - } - - keys, kerr := parsePath(path) - if kerr != nil { - return nil, kerr - } - - vals, verr := valuesForArray(keys, mv) - if verr != nil { - return nil, verr // Vals may be nil, but return empty array. - } - - // Need to handle subkeys ... only return members of vals that satisfy conditions. - retvals := make([]interface{}, 0) - for _, v := range vals { - if hasSubKeys(v, subKeyMap) { - retvals = append(retvals, v) - } - } - return retvals, nil -} - -func valuesForArray(keys []*key, m Map) ([]interface{}, error) { - var tmppath string - var haveFirst bool - var vals []interface{} - var verr error - - lastkey := len(keys) - 1 - for i := 0; i <= lastkey; i++ { - if !haveFirst { - tmppath = keys[i].name - haveFirst = true - } else { - tmppath += "." + keys[i].name - } - - // Look-ahead: explode wildcards and unindexed arrays. - // Need to handle un-indexed list recursively: - // e.g., path is "stuff.data[0]" rather than "stuff[0].data[0]". - // Need to treat it as "stuff[0].data[0]", "stuff[1].data[0]", ... - if !keys[i].isArray && i < lastkey && keys[i+1].isArray { - // Can't pass subkeys because we may not be at literal end of path. - vv, vverr := m.oldValuesForPath(tmppath) - if vverr != nil { - return nil, vverr - } - for _, v := range vv { - // See if we can walk the value. - am, ok := v.(map[string]interface{}) - if !ok { - continue - } - // Work the backend. - nvals, nvalserr := valuesForArray(keys[i+1:], Map(am)) - if nvalserr != nil { - return nil, nvalserr - } - vals = append(vals, nvals...) - } - break // have recursed the whole path - return - } - - if keys[i].isArray || i == lastkey { - // Don't pass subkeys because may not be at literal end of path. - vals, verr = m.oldValuesForPath(tmppath) - } else { - continue - } - if verr != nil { - return nil, verr - } - - if i == lastkey && !keys[i].isArray { - break - } - - // Now we're looking at an array - supposedly. - // Is index in range of vals? - if len(vals) <= keys[i].position { - vals = nil - break - } - - // Return the array member of interest, if at end of path. - if i == lastkey { - vals = vals[keys[i].position:(keys[i].position + 1)] - break - } - - // Extract the array member of interest. - am := vals[keys[i].position:(keys[i].position + 1)] - - // must be a map[string]interface{} value so we can keep walking the path - amm, ok := am[0].(map[string]interface{}) - if !ok { - vals = nil - break - } - - m = Map(amm) - haveFirst = false - } - - return vals, nil -} - -type key struct { - name string - isArray bool - position int -} - -func parsePath(s string) ([]*key, error) { - keys := strings.Split(s, ".") - - ret := make([]*key, 0) - - for i := 0; i < len(keys); i++ { - if keys[i] == "" { - continue - } - - newkey := new(key) - if strings.Index(keys[i], "[") < 0 { - newkey.name = keys[i] - ret = append(ret, newkey) - continue - } - - p := strings.Split(keys[i], "[") - newkey.name = p[0] - p = strings.Split(p[1], "]") - if p[0] == "" { // no right bracket - return nil, fmt.Errorf("no right bracket on key index: %s", keys[i]) - } - // convert p[0] to a int value - pos, nerr := strconv.ParseInt(p[0], 10, 32) - if nerr != nil { - return nil, fmt.Errorf("cannot convert index to int value: %s", p[0]) - } - newkey.position = int(pos) - newkey.isArray = true - ret = append(ret, newkey) - } - - return ret, nil -} - -// legacy ValuesForPath() - now wrapped to handle special case of indexed arrays in 'path'. -func (mv Map) oldValuesForPath(path string, subkeys ...string) ([]interface{}, error) { - m := map[string]interface{}(mv) - var subKeyMap map[string]interface{} - if len(subkeys) > 0 { - var err error - subKeyMap, err = getSubKeyMap(subkeys...) - if err != nil { - return nil, err - } - } - - keys := strings.Split(path, ".") - if keys[len(keys)-1] == "" { - keys = keys[:len(keys)-1] - } - // ivals := make([]interface{}, 0) - // valuesForKeyPath(&ivals, m, keys, subKeyMap) - // return ivals, nil - ivals := make([]interface{}, 0, defaultArraySize) - var cnt int - valuesForKeyPath(&ivals, &cnt, m, keys, subKeyMap) - return ivals[:cnt], nil -} - -func valuesForKeyPath(ret *[]interface{}, cnt *int, m interface{}, keys []string, subkeys map[string]interface{}) { - lenKeys := len(keys) - - // load 'm' values into 'ret' - // expand any lists - if lenKeys == 0 { - switch m.(type) { - case map[string]interface{}: - if subkeys != nil { - if ok := hasSubKeys(m, subkeys); !ok { - return - } - } - *ret = append(*ret, m) - *cnt++ - case []interface{}: - for i, v := range m.([]interface{}) { - if subkeys != nil { - if ok := hasSubKeys(v, subkeys); !ok { - continue // only load list members with subkeys - } - } - *ret = append(*ret, (m.([]interface{}))[i]) - *cnt++ - } - default: - if subkeys != nil { - return // must be map[string]interface{} if there are subkeys - } - *ret = append(*ret, m) - *cnt++ - } - return - } - - // key of interest - key := keys[0] - switch key { - case "*": // wildcard - scan all values - switch m.(type) { - case map[string]interface{}: - for _, v := range m.(map[string]interface{}) { - // valuesForKeyPath(ret, v, keys[1:], subkeys) - valuesForKeyPath(ret, cnt, v, keys[1:], subkeys) - } - case []interface{}: - for _, v := range m.([]interface{}) { - switch v.(type) { - // flatten out a list of maps - keys are processed - case map[string]interface{}: - for _, vv := range v.(map[string]interface{}) { - // valuesForKeyPath(ret, vv, keys[1:], subkeys) - valuesForKeyPath(ret, cnt, vv, keys[1:], subkeys) - } - default: - // valuesForKeyPath(ret, v, keys[1:], subkeys) - valuesForKeyPath(ret, cnt, v, keys[1:], subkeys) - } - } - } - default: // key - must be map[string]interface{} - switch m.(type) { - case map[string]interface{}: - if v, ok := m.(map[string]interface{})[key]; ok { - // valuesForKeyPath(ret, v, keys[1:], subkeys) - valuesForKeyPath(ret, cnt, v, keys[1:], subkeys) - } - case []interface{}: // may be buried in list - for _, v := range m.([]interface{}) { - switch v.(type) { - case map[string]interface{}: - if vv, ok := v.(map[string]interface{})[key]; ok { - // valuesForKeyPath(ret, vv, keys[1:], subkeys) - valuesForKeyPath(ret, cnt, vv, keys[1:], subkeys) - } - } - } - } - } -} - -// hasSubKeys() - interface{} equality works for string, float64, bool -// 'v' must be a map[string]interface{} value to have subkeys -// 'a' can have k:v pairs with v.(string) == "*", which is treated like a wildcard. -func hasSubKeys(v interface{}, subkeys map[string]interface{}) bool { - if len(subkeys) == 0 { - return true - } - - switch v.(type) { - case map[string]interface{}: - // do all subKey name:value pairs match? - mv := v.(map[string]interface{}) - for skey, sval := range subkeys { - isNotKey := false - if skey[:1] == "!" { // a NOT-key - skey = skey[1:] - isNotKey = true - } - vv, ok := mv[skey] - if !ok { // key doesn't exist - if isNotKey { // key not there, but that's what we want - if kv, ok := sval.(string); ok && kv == "*" { - continue - } - } - return false - } - // wildcard check - if kv, ok := sval.(string); ok && kv == "*" { - if isNotKey { // key is there, and we don't want it - return false - } - continue - } - switch sval.(type) { - case string: - if s, ok := vv.(string); ok && s == sval.(string) { - if isNotKey { - return false - } - continue - } - case bool: - if b, ok := vv.(bool); ok && b == sval.(bool) { - if isNotKey { - return false - } - continue - } - case float64: - if f, ok := vv.(float64); ok && f == sval.(float64) { - if isNotKey { - return false - } - continue - } - } - // key there but didn't match subkey value - if isNotKey { // that's what we want - continue - } - return false - } - // all subkeys matched - return true - } - - // not a map[string]interface{} value, can't have subkeys - return false -} - -// Generate map of key:value entries as map[string]string. -// 'kv' arguments are "name:value" pairs: attribute keys are designated with prepended hyphen, '-'. -// If len(kv) == 0, the return is (nil, nil). -func getSubKeyMap(kv ...string) (map[string]interface{}, error) { - if len(kv) == 0 { - return nil, nil - } - m := make(map[string]interface{}, 0) - for _, v := range kv { - vv := strings.Split(v, ":") - switch len(vv) { - case 2: - m[vv[0]] = interface{}(vv[1]) - case 3: - switch vv[3] { - case "string", "char", "text": - m[vv[0]] = interface{}(vv[1]) - case "bool", "boolean": - // ParseBool treats "1"==true & "0"==false - b, err := strconv.ParseBool(vv[1]) - if err != nil { - return nil, fmt.Errorf("can't convert subkey value to bool: %s", vv[1]) - } - m[vv[0]] = interface{}(b) - case "float", "float64", "num", "number", "numeric": - f, err := strconv.ParseFloat(vv[1], 64) - if err != nil { - return nil, fmt.Errorf("can't convert subkey value to float: %s", vv[1]) - } - m[vv[0]] = interface{}(f) - default: - return nil, fmt.Errorf("unknown subkey conversion spec: %s", v) - } - default: - return nil, fmt.Errorf("unknown subkey spec: %s", v) - } - } - return m, nil -} - -// ------------------------------- END of valuesFor ... ---------------------------- - -// ----------------------- locate where a key value is in the tree ------------------- - -//----------------------------- find all paths to a key -------------------------------- - -// Get all paths through Map, 'mv', (in dot-notation) that terminate with the specified key. -// Results can be used with ValuesForPath. -func (mv Map) PathsForKey(key string) []string { - m := map[string]interface{}(mv) - breadbasket := make(map[string]bool, 0) - breadcrumbs := "" - - hasKeyPath(breadcrumbs, m, key, breadbasket) - if len(breadbasket) == 0 { - return nil - } - - // unpack map keys to return - res := make([]string, len(breadbasket)) - var i int - for k := range breadbasket { - res[i] = k - i++ - } - - return res -} - -// Extract the shortest path from all possible paths - from PathsForKey() - in Map, 'mv'.. -// Paths are strings using dot-notation. -func (mv Map) PathForKeyShortest(key string) string { - paths := mv.PathsForKey(key) - - lp := len(paths) - if lp == 0 { - return "" - } - if lp == 1 { - return paths[0] - } - - shortest := paths[0] - shortestLen := len(strings.Split(shortest, ".")) - - for i := 1; i < len(paths); i++ { - vlen := len(strings.Split(paths[i], ".")) - if vlen < shortestLen { - shortest = paths[i] - shortestLen = vlen - } - } - - return shortest -} - -// hasKeyPath - if the map 'key' exists append it to KeyPath.path and increment KeyPath.depth -// This is really just a breadcrumber that saves all trails that hit the prescribed 'key'. -func hasKeyPath(crumbs string, iv interface{}, key string, basket map[string]bool) { - switch iv.(type) { - case map[string]interface{}: - vv := iv.(map[string]interface{}) - if _, ok := vv[key]; ok { - if crumbs == "" { - crumbs = key - } else { - crumbs += "." + key - } - // *basket = append(*basket, crumb) - basket[crumbs] = true - } - // walk on down the path, key could occur again at deeper node - for k, v := range vv { - // create a new breadcrumb, intialized with the one we have - var nbc string - if crumbs == "" { - nbc = k - } else { - nbc = crumbs + "." + k - } - hasKeyPath(nbc, v, key, basket) - } - case []interface{}: - // crumb-trail doesn't change, pass it on - for _, v := range iv.([]interface{}) { - hasKeyPath(crumbs, v, key, basket) - } - } -} - -// Returns the first found value for the path. -func (mv Map) ValueForPath(path string) (interface{}, error) { - vals, err := mv.ValuesForPath(path) - if err != nil { - return nil, err - } - if len(vals) == 0 { - return nil, errors.New("ValueForPath: path not found") - } - return vals[0], nil -} - -// Returns the first found value for the path as a string. -func (mv Map) ValueForPathString(path string) (string, error) { - vals, err := mv.ValuesForPath(path) - if err != nil { - return "", err - } - if len(vals) == 0 { - return "", errors.New("ValueForPath: path not found") - } - val := vals[0] - switch str := val.(type) { - case string: - return str, nil - default: - return "", fmt.Errorf("ValueForPath: unsupported type: %T", str) - } -} - -// Returns the first found value for the path as a string. -// If the path is not found then it returns an empty string. -func (mv Map) ValueOrEmptyForPathString(path string) string { - str, _ := mv.ValueForPathString(path) - return str -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues_test.go deleted file mode 100644 index 0626df21..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/keyvalues_test.go +++ /dev/null @@ -1,446 +0,0 @@ -// keyvalues_test.go - test keyvalues.go methods - -package mxj - -import ( - // "bytes" - "fmt" - // "io" - "testing" -) - -func TestKVHeader(t *testing.T) { - fmt.Println("\n---------------- keyvalues_test.go ...\n") -} - -var doc1 = []byte(` - - - - William T. Gaddis - The Recognitions - One of the great seminal American novels of the 20th century. - - - Austin Tappan Wright - Islandia - An example of earlier 20th century American utopian fiction. - - - John Hawkes - The Beetle Leg - A lyrical novel about the construction of Ft. Peck Dam in Montana. - - - - T.E. - Porter - - King's Day - A magical novella. - - - -`) - -var doc2 = []byte(` - - - - William T. Gaddis - The Recognitions - One of the great seminal American novels of the 20th century. - - - Something else. - -`) - -// the basic demo/test case - a small bibliography with mixed element types -func TestPathsForKey(t *testing.T) { - fmt.Println("PathsForKey, doc1 ...") - m, merr := NewMapXml(doc1) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("PathsForKey, doc1#author") - ss := m.PathsForKey("author") - fmt.Println("... ss:", ss) - - fmt.Println("PathsForKey, doc1#books") - ss = m.PathsForKey("books") - fmt.Println("... ss:", ss) - - fmt.Println("PathsForKey, doc2 ...") - m, merr = NewMapXml(doc2) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("PathForKey, doc2#book") - ss = m.PathsForKey("book") - fmt.Println("... ss:", ss) - - fmt.Println("PathForKeyShortest, doc2#book") - s := m.PathForKeyShortest("book") - fmt.Println("... s :", s) -} - -func TestValuesForKey(t *testing.T) { - fmt.Println("ValuesForKey ...") - m, merr := NewMapXml(doc1) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("ValuesForKey, doc1#author") - ss, sserr := m.ValuesForKey("author") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForKey, doc1#book") - ss, sserr = m.ValuesForKey("book") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForKey, doc1#book,-seq:3") - ss, sserr = m.ValuesForKey("book", "-seq:3") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForKey, doc1#book, author:William T. Gaddis") - ss, sserr = m.ValuesForKey("book", "author:William T. Gaddis") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForKey, doc1#author, -seq:1") - ss, sserr = m.ValuesForKey("author", "-seq:1") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { // should be len(ss) == 0 - fmt.Println("... ss.v:", v) - } -} - -func TestValuesForPath(t *testing.T) { - fmt.Println("ValuesForPath ...") - m, merr := NewMapXml(doc1) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("ValuesForPath, doc.books.book.author") - ss, sserr := m.ValuesForPath("doc.books.book.author") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.books.book") - ss, sserr = m.ValuesForPath("doc.books.book") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.books.book -seq=3") - ss, sserr = m.ValuesForPath("doc.books.book", "-seq:3") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.books.* -seq=3") - ss, sserr = m.ValuesForPath("doc.books.*", "-seq:3") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.*.* -seq=3") - ss, sserr = m.ValuesForPath("doc.*.*", "-seq:3") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } -} - -func TestValuesForNotKey(t *testing.T) { - fmt.Println("ValuesForNotKey ...") - m, merr := NewMapXml(doc1) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("ValuesForPath, doc.books.book !author:William T. Gaddis") - ss, sserr := m.ValuesForPath("doc.books.book", "!author:William T. Gaddis") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.books.book !author:*") - ss, sserr = m.ValuesForPath("doc.books.book", "!author:*") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { // expect len(ss) == 0 - fmt.Println("... ss.v:", v) - } - - fmt.Println("ValuesForPath, doc.books.book !unknown:*") - ss, sserr = m.ValuesForPath("doc.books.book", "!unknown:*") - if sserr != nil { - t.Fatal("sserr:", sserr.Error()) - } - for _, v := range ss { - fmt.Println("... ss.v:", v) - } -} - -func TestIAHeader(t *testing.T) { - fmt.Println("\n---------------- indexedarray_test.go ...\n") -} - -var ak_data = []byte(`{ "section1":{"data" : [{"F1" : "F1 data","F2" : "F2 data"},{"F1" : "demo 123","F2" : "abc xyz"}]}}`) -var j_data = []byte(`{ "stuff":[ { "data":[ { "F":1 }, { "F":2 }, { "F":3 } ] }, { "data":[ 4, 5, 6 ] } ] }`) -var x_data = []byte(` - - - - 1 - - - 2 - - - 3 - - - - - 4 - - - 5 - - - 6 - - -`) - -func TestValuesForIndexedArray(t *testing.T) { - j_main(t) - x_main(t) - ak_main(t) -} - -func ak_main(t *testing.T) { - fmt.Println("\nak_data:", string(ak_data)) - m, merr := NewMapJson(ak_data) - if merr != nil { - t.Fatal("merr:", merr.Error()) - return - } - fmt.Println("m:", m) - - v, verr := m.ValuesForPath("section1.data[0].F1") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("section1.data[0].F1:", v) -} - -func j_main(t *testing.T) { - fmt.Println("j_data:", string(j_data)) - m, merr := NewMapJson(j_data) - if merr != nil { - t.Fatal("merr:", merr.Error()) - return - } - fmt.Println("m:", m) - - v, verr := m.ValuesForPath("stuff[0]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[0]:", v) - - v, verr = m.ValuesForPath("stuff.data") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.data:", v) - - v, verr = m.ValuesForPath("stuff[0].data") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[0].data:", v) - - v, verr = m.ValuesForPath("stuff.data[0]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.data[0]:", v) - - v, verr = m.ValuesForPath("stuff.*[2]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.*[2]:", v) - - v, verr = m.ValuesForPath("stuff.data.F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.data.F:", v) - - v, verr = m.ValuesForPath("*.*.F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("*.*.F:", v) - - v, verr = m.ValuesForPath("stuff.data[0].F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.data[0].F:", v) - - v, verr = m.ValuesForPath("stuff.data[1].F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff.data[1].F:", v) - - v, verr = m.ValuesForPath("stuff[0].data[2]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[0].data[2]:", v) - - v, verr = m.ValuesForPath("stuff[1].data[1]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[1].data[1]:", v) - - v, verr = m.ValuesForPath("stuff[1].data[1].F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[1].data[1].F", v) - - v, verr = m.ValuesForPath("stuff[1].data.F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("stuff[1].data.F:", v) -} - -func x_main(t *testing.T) { - fmt.Println("\nx_data:", string(x_data)) - m, merr := NewMapXml(x_data) - if merr != nil { - t.Fatal("merr:", merr.Error()) - return - } - fmt.Println("m:", m) - - v, verr := m.ValuesForPath("doc.stuff[0]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff[0]:", v) - - v, verr = m.ValuesForPath("doc.stuff.data[0]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff.data[0]:", v) - - v, verr = m.ValuesForPath("doc.stuff.data[0]", "-seq:2.1") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff.data[0] -seq:2.1:", v) - - v, verr = m.ValuesForPath("doc.stuff.data[0].F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff.data[0].F:", v) - - v, verr = m.ValuesForPath("doc.stuff[0].data[2]") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff[0].data[2]:", v) - - v, verr = m.ValuesForPath("doc.stuff[1].data[1].F") - if verr != nil { - t.Fatal("verr:", verr.Error()) - } - fmt.Println("doc.stuff[1].data[1].F:", v) -} - -func TestValueForPath(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - }, - } - mv := Map(m) - - v, err := mv.ValueForPath("Div.Colour") - if err != nil { - t.Fatal(err) - } - if str, ok := v.(string); !ok || str != "blue" { - t.Fatal("wrong value") - } -} - -func TestValueForPathString(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - }, - } - mv := Map(m) - - str, err := mv.ValueForPathString("Div.Colour") - if err != nil { - t.Fatal(err) - } - if str != "blue" { - t.Fatal("wrong value") - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode.go b/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode.go deleted file mode 100644 index 99f27165..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode.go +++ /dev/null @@ -1,82 +0,0 @@ -package mxj - -// leafnode.go - return leaf nodes with paths and values for the Map -// inspired by: https://groups.google.com/forum/#!topic/golang-nuts/3JhuVKRuBbw - -import ( - "strconv" -) - -const ( - NoAttributes = true // suppress LeafNode values that are attributes -) - -// LeafNode - a terminal path value in a Map. -// For XML Map values it represents an attribute or simple element value - of type -// string unless Map was created using Cast flag. For JSON Map values it represents -// a string, numeric, boolean, or null value. -type LeafNode struct { - Path string // a dot-notation representation of the path with array subscripting - Value interface{} // the value at the path termination -} - -// LeafNodes - returns an array of all LeafNode values for the Map. -// The option no_attr argument suppresses attribute values (keys with prepended hyphen, '-') -// as well as the "#text" key for the associated simple element value. -func (mv Map) LeafNodes(no_attr ...bool) []LeafNode { - var a bool - if len(no_attr) == 1 { - a = no_attr[0] - } - - l := make([]LeafNode, 0) - getLeafNodes("", "", map[string]interface{}(mv), &l, a) - return l -} - -func getLeafNodes(path, node string, mv interface{}, l *[]LeafNode, noattr bool) { - // if stripping attributes, then also strip "#text" key - if !noattr || node != "#text" { - if path != "" && node[:1] != "[" { - path += "." - } - path += node - } - switch mv.(type) { - case map[string]interface{}: - for k, v := range mv.(map[string]interface{}) { - if noattr && k[:1] == "-" { - continue - } - getLeafNodes(path, k, v, l, noattr) - } - case []interface{}: - for i, v := range mv.([]interface{}) { - getLeafNodes(path, "["+strconv.Itoa(i)+"]", v, l, noattr) - } - default: - // can't walk any further, so create leaf - n := LeafNode{path, mv} - *l = append(*l, n) - } -} - -// LeafPaths - all paths that terminate in LeafNode values. -func (mv Map) LeafPaths(no_attr ...bool) []string { - ln := mv.LeafNodes() - ss := make([]string, len(ln)) - for i := 0; i < len(ln); i++ { - ss[i] = ln[i].Path - } - return ss -} - -// LeafValues - all terminal values in the Map. -func (mv Map) LeafValues(no_attr ...bool) []interface{} { - ln := mv.LeafNodes() - vv := make([]interface{}, len(ln)) - for i := 0; i < len(ln); i++ { - vv[i] = ln[i].Value - } - return vv -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode_test.go deleted file mode 100644 index 9cb9dd71..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/leafnode_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package mxj - -import ( - "fmt" - "testing" -) - -func TestLNHeader(t *testing.T) { - fmt.Println("\n---------------- leafnode_test.go ...") -} - -func TestLeafNodes(t *testing.T) { - json1 := []byte(`{ - "friends": [ - { - "skills": [ - 44, 12 - ] - } - ] - }`) - - json2 := []byte(`{ - "friends": - { - "skills": [ - 44, 12 - ] - } - - }`) - - m, _ := NewMapJson(json1) - ln := m.LeafNodes() - fmt.Println("\njson1-LeafNodes:") - for _, v := range ln { - fmt.Printf("%#v\n", v) - } - p := m.LeafPaths() - fmt.Println("\njson1-LeafPaths:") - for _, v := range p { - fmt.Printf("%#v\n", v) - } - - m, _ = NewMapJson(json2) - ln = m.LeafNodes() - fmt.Println("\njson2-LeafNodes:") - for _, v := range ln { - fmt.Printf("%#v\n", v) - } - v := m.LeafValues() - fmt.Println("\njson1-LeafValues:") - for _, v := range v { - fmt.Printf("%#v\n", v) - } - - json3 := []byte(`{ "a":"list", "of":["data", "of", 3, "types", true]}`) - m, _ = NewMapJson(json3) - ln = m.LeafNodes() - fmt.Println("\njson3-LeafNodes:") - for _, v := range ln { - fmt.Printf("%#v\n", v) - } - v = m.LeafValues() - fmt.Println("\njson3-LeafValues:") - for _, v := range v { - fmt.Printf("%#v\n", v) - } - p = m.LeafPaths() - fmt.Println("\njson3-LeafPaths:") - for _, v := range p { - fmt.Printf("%#v\n", v) - } - - xmldata2 := []byte(` - - Item 2 is blue - - - - - `) - m, err := NewMapXml(xmldata2) - if err != nil { - t.Fatal(err.Error()) - } - fmt.Println("\nxml2data2-LeafValues:") - ln = m.LeafNodes() - for _, v := range ln { - fmt.Printf("%#v\n", v) - } - fmt.Println("\nxml2data2-LeafValues(NoAttributes):") - ln = m.LeafNodes(NoAttributes) - for _, v := range ln { - fmt.Printf("%#v\n", v) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/mxj.go b/Godeps/_workspace/src/github.com/clbanning/mxj/mxj.go deleted file mode 100644 index 8e90c32b..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/mxj.go +++ /dev/null @@ -1,107 +0,0 @@ -// mxj - A collection of map[string]interface{} and associated XML and JSON utilities. -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -package mxj - -import ( - "fmt" - "strconv" -) - -const ( - Cast = true // for clarity - e.g., mxj.NewMapXml(doc, mxj.Cast) - SafeEncoding = true // ditto - e.g., mv.Json(mxj.SafeEncoding) -) - -type Map map[string]interface{} - -// Allocate a Map. -func New() Map { - m := make(map[string]interface{}, 0) - return m -} - -// Cast a Map to map[string]interface{} -func (mv Map) Old() map[string]interface{} { - return mv -} - -// Return a copy of mv as a newly allocated Map. If the Map only contains string, -// numeric, map[string]interface{}, and []interface{} values, then it can be thought -// of as a "deep copy." Copying a structure (or structure reference) value is subject -// to the noted restrictions. -// NOTE: If 'mv' includes structure values with, possibly, JSON encoding tags -// then only public fields of the structure are in the new Map - and with -// keys that conform to any encoding tag instructions. The structure itself will -// be represented as a map[string]interface{} value. -func (mv Map) Copy() (Map, error) { - // this is the poor-man's deep copy - // not efficient, but it works - j, jerr := mv.Json() - // must handle, we don't know how mv got built - if jerr != nil { - return nil, jerr - } - return NewMapJson(j) -} - -// --------------- StringIndent ... from x2j.WriteMap ------------- - -// Pretty print a Map. -func (mv Map) StringIndent(offset ...int) string { - return writeMap(map[string]interface{}(mv), offset...) -} - -// writeMap - dumps the map[string]interface{} for examination. -// 'offset' is initial indentation count; typically: Write(m). -func writeMap(m interface{}, offset ...int) string { - var indent int - if len(offset) == 1 { - indent = offset[0] - } - - var s string - switch m.(type) { - case nil: - return "[nil] nil" - case string: - return "[string] " + m.(string) - case float64: - return "[float64] " + strconv.FormatFloat(m.(float64), 'e', 2, 64) - case bool: - return "[bool] " + strconv.FormatBool(m.(bool)) - case []interface{}: - s += "[[]interface{}]" - for i, v := range m.([]interface{}) { - s += "\n" - for i := 0; i < indent; i++ { - s += " " - } - s += "[item: " + strconv.FormatInt(int64(i), 10) + "]" - switch v.(type) { - case string, float64, bool: - s += "\n" - default: - // noop - } - for i := 0; i < indent; i++ { - s += " " - } - s += writeMap(v, indent+1) - } - case map[string]interface{}: - for k, v := range m.(map[string]interface{}) { - s += "\n" - for i := 0; i < indent; i++ { - s += " " - } - s += k + " :" + writeMap(v, indent+1) - } - default: - // shouldn't ever be here ... - s += fmt.Sprintf("[unknown] %#v", m) - } - return s -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/mxj_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/mxj_test.go deleted file mode 100644 index 319e09e5..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/mxj_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package mxj - -import ( - "fmt" - "testing" -) - -func TestMxjHeader(t *testing.T) { - fmt.Println("\n---------------- mxj_test.go ...\n") -} - -func TestMap(t *testing.T) { - m := New() - - m["key"] = interface{}("value") - v := map[string]interface{}{"bool": true, "float": 3.14159, "string": "Now is the time"} - vv := []interface{}{3.1415962535, false, "for all good men"} - v["listkey"] = interface{}(vv) - m["newkey"] = interface{}(v) - - fmt.Println("TestMap, m:", m) - fmt.Println("TestMap, StringIndent:", m.StringIndent()) - - o := interface{}(m.Old()) - switch o.(type) { - case map[string]interface{}: - // do nothing - default: - t.Fatal("invalid type for m.Old()") - } - - m, _ = NewMapXml([]byte(`HelloWorld`)) - fmt.Println("TestMap, m_fromXML:", m) - fmt.Println("TestMap, StringIndent:", m.StringIndent()) - - mm, _ := m.Copy() - fmt.Println("TestMap, m.Copy():", mm) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/newmap.go b/Godeps/_workspace/src/github.com/clbanning/mxj/newmap.go deleted file mode 100644 index fc1320c0..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/newmap.go +++ /dev/null @@ -1,183 +0,0 @@ -// mxj - A collection of map[string]interface{} and associated XML and JSON utilities. -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// remap.go - build a new Map from the current Map based on keyOld:keyNew mapppings -// keys can use dot-notation, keyOld can use wildcard, '*' -// -// Computational strategy - -// Using the key path - []string - traverse a new map[string]interface{} and -// insert the oldVal as the newVal when we arrive at the end of the path. -// If the type at the end is nil, then that is newVal -// If the type at the end is a singleton (string, float64, bool) an array is created. -// If the type at the end is an array, newVal is just appended. -// If the type at the end is a map, it is inserted if possible or the map value -// is converted into an array if necessary. - -package mxj - -import ( - "errors" - "strings" -) - -// (Map)NewMap - create a new Map from data in the current Map. -// 'keypairs' are key mappings "oldKey:newKey" and specify that the current value of 'oldKey' -// should be the value for 'newKey' in the returned Map. -// - 'oldKey' supports dot-notation as described for (Map)ValuesForPath() -// - 'newKey' supports dot-notation but with no wildcards, '*', or indexed arrays -// - "oldKey" is shorthand for for the keypair value "oldKey:oldKey" -// - "oldKey:" and ":newKey" are invalid keypair values -// - if 'oldKey' does not exist in the current Map, it is not written to the new Map. -// "null" is not supported unless it is the current Map. -// - see newmap_test.go for several syntax examples -// -// NOTE: mv.NewMap() == mxj.New(). -func (mv Map) NewMap(keypairs ...string) (Map, error) { - n := make(map[string]interface{}, 0) - if len(keypairs) == 0 { - return n, nil - } - - // loop through the pairs - var oldKey, newKey string - var path []string - for _, v := range keypairs { - if len(v) == 0 { - continue // just skip over empty keypair arguments - } - - // initialize oldKey, newKey and check - vv := strings.Split(v, ":") - if len(vv) > 2 { - return n, errors.New("oldKey:newKey keypair value not valid - " + v) - } - if len(vv) == 1 { - oldKey, newKey = vv[0], vv[0] - } else { - oldKey, newKey = vv[0], vv[1] - } - strings.TrimSpace(oldKey) - strings.TrimSpace(newKey) - if i := strings.Index(newKey, "*"); i > -1 { - return n, errors.New("newKey value cannot contain wildcard character - " + v) - } - if i := strings.Index(newKey, "["); i > -1 { - return n, errors.New("newKey value cannot contain indexed arrays - " + v) - } - if oldKey == "" || newKey == "" { - return n, errors.New("oldKey or newKey is not specified - " + v) - } - - // get oldKey value - oldVal, err := mv.ValuesForPath(oldKey) - if err != nil { - return n, err - } - if len(oldVal) == 0 { - continue // oldKey has no value, may not exist in mv - } - - // break down path - path = strings.Split(newKey, ".") - if path[len(path)-1] == "" { // ignore a trailing dot in newKey spec - path = path[:len(path)-1] - } - - addNewVal(&n, path, oldVal) - } - - return n, nil -} - -// navigate 'n' to end of path and add val -func addNewVal(n *map[string]interface{}, path []string, val []interface{}) { - // newVal - either singleton or array - var newVal interface{} - if len(val) == 1 { - newVal = val[0] // is type interface{} - } else { - newVal = interface{}(val) - } - - // walk to the position of interest, create it if necessary - m := (*n) // initialize map walker - var k string // key for m - lp := len(path) - 1 // when to stop looking - for i := 0; i < len(path); i++ { - k = path[i] - if i == lp { - break - } - var nm map[string]interface{} // holds position of next-map - switch m[k].(type) { - case nil: // need a map for next node in path, so go there - nm = make(map[string]interface{}, 0) - m[k] = interface{}(nm) - m = m[k].(map[string]interface{}) - case map[string]interface{}: - // OK - got somewhere to walk to, go there - m = m[k].(map[string]interface{}) - case []interface{}: - // add a map and nm points to new map unless there's already - // a map in the array, then nm points there - // The placement of the next value in the array is dependent - // on the sequence of members - could land on a map or a nil - // value first. TODO: how to test this. - a := make([]interface{}, 0) - var foundmap bool - for _, vv := range m[k].([]interface{}) { - switch vv.(type) { - case nil: // doesn't appear that this occurs, need a test case - if foundmap { // use the first one in array - a = append(a, vv) - continue - } - nm = make(map[string]interface{}, 0) - a = append(a, interface{}(nm)) - foundmap = true - case map[string]interface{}: - if foundmap { // use the first one in array - a = append(a, vv) - continue - } - nm = vv.(map[string]interface{}) - a = append(a, vv) - foundmap = true - default: - a = append(a, vv) - } - } - // no map found in array - if !foundmap { - nm = make(map[string]interface{}, 0) - a = append(a, interface{}(nm)) - } - m[k] = interface{}(a) // must insert in map - m = nm - default: // it's a string, float, bool, etc. - aa := make([]interface{}, 0) - nm = make(map[string]interface{}, 0) - aa = append(aa, m[k], nm) - m[k] = interface{}(aa) - m = nm - } - } - - // value is nil, array or a singleton of some kind - // initially m.(type) == map[string]interface{} - v := m[k] - switch v.(type) { - case nil: // initialized - m[k] = newVal - case []interface{}: - a := m[k].([]interface{}) - a = append(a, newVal) - m[k] = interface{}(a) - default: // v exists:string, float64, bool, map[string]interface, etc. - a := make([]interface{}, 0) - a = append(a, v, newVal) - m[k] = interface{}(a) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/newmap_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/newmap_test.go deleted file mode 100644 index 7e3fdfea..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/newmap_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package mxj - -import ( - "bytes" - "fmt" - "io" - "testing" -) - -func TestNewMapHeader(t *testing.T) { - fmt.Println("\n---------------- newmap_test.go ...\n") -} - -func TestNewMap(t *testing.T) { - j := []byte(`{ "A":"this", "B":"is", "C":"a", "D":"test" }`) - fmt.Println("j:", string(j)) - - m, _ := NewMapJson(j) - fmt.Printf("m: %#v\n", m) - - fmt.Println("\n", `eval - m.NewMap("A:AA", "B:BB", "C:cc", "D:help")`) - n, err := m.NewMap("A:AA", "B:BB", "C:cc", "D:help") - if err != nil { - fmt.Println("err:", err.Error()) - } - j, _ = n.Json() - fmt.Println("n.Json():", string(j)) - x, _ := n.Xml() - fmt.Println("n.Xml():\n", string(x)) - x, _ = n.XmlIndent("", " ") - fmt.Println("n.XmlIndent():\n", string(x)) - - fmt.Println("\n", `eval - m.NewMap("A:AA.A", "B:AA.B", "C:AA.B.cc", "D:hello.help")`) - n, err = m.NewMap("A:AA.A", "B:AA.B", "C:AA.B.cc", "D:hello.help") - if err != nil { - fmt.Println("err:", err.Error()) - } - j, _ = n.Json() - fmt.Println("n.Json():", string(j)) - x, _ = n.Xml() - fmt.Println("n.Xml():\n", string(x)) - x, _ = n.XmlIndent("", " ") - fmt.Println("n.XmlIndent():\n", string(x)) - - var keypairs = []string{"A:xml.AA", "B:xml.AA.hello.again", "C:xml.AA", "D:xml.AA.hello.help"} - fmt.Println("\n", `eval - m.NewMap keypairs:`, keypairs) - n, err = m.NewMap(keypairs...) - if err != nil { - fmt.Println("err:", err.Error()) - } - j, _ = n.Json() - fmt.Println("n.Json():", string(j)) - x, _ = n.Xml() - fmt.Println("n.Xml():\n", string(x)) - x, _ = n.XmlIndent("", " ") - fmt.Println("n.XmlIndent():\n", string(x)) -} - -// Need to normalize from an XML stream the values for "netid" and "idnet". -// Solution: make everything "netid" -// Demo how to re-label a key using mv.NewMap() - -var msg1 = []byte(` - - - - no - default:text - default:word - - -`) - -var msg2 = []byte(` - - - - yes - default:text - default:word - - -`) - -func TestNetId(t *testing.T) { - // let's create a message stream - buf := new(bytes.Buffer) - // load a couple of messages into it - _, _ = buf.Write(msg1) - _, _ = buf.Write(msg2) - - n := 0 - for { - n++ - // read the stream as Map values - quit on io.EOF - m, raw, merr := NewMapXmlReaderRaw(buf) - if merr != nil && merr != io.EOF { - // handle error - for demo we just print it and continue - fmt.Printf("msg: %d - merr: %s\n", n, merr.Error()) - continue - } else if merr == io.EOF { - break - } - - // the first keypair retains values if data correct - // the second keypair relabels "idnet" to "netid" - n, _ := m.NewMap("data.netid", "data.idnet:data.netid") - x, _ := n.XmlIndent("", " ") - - fmt.Println("original value:", string(raw)) - fmt.Println("new value:") - fmt.Println(string(x)) - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/readme.md b/Godeps/_workspace/src/github.com/clbanning/mxj/readme.md deleted file mode 100644 index 76cff5df..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/readme.md +++ /dev/null @@ -1,113 +0,0 @@ -

mxj - to/from maps, XML and JSON

-Marshal/Unmarshal XML to/from JSON and `map[string]interface{}` values, and extract/modify values from maps by key or key-path, including wildcards. - -mxj supplants the legacy x2j and j2x packages. If you want the old syntax, use mxj/x2j and mxj/j2x packages. - -

Notices

- 2014-11-09: IncludeTagSeqNum() adds "_seq" key with XML doc positional information. - (NOTE: PreserveXmlList() is similar and will be here soon.) - 2014-09-18: inspired by NYTimes fork, added PrependAttrWithHyphen() to allow stripping hyphen from attribute tag. - 2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML. - 2014-04-28: ValuesForPath() and NewMap() now accept path with indexed array references. - -

Basic Unmarshal XML / JSON / struct

-
type Map map[string]interface{}
- -Create a `Map` value, 'm', from any `map[string]interface{}` value, 'v': -
m := Map(v)
- -Unmarshal / marshal XML as a `Map` value, 'm': -
m, err := NewMapXml(xmlValue) // unmarshal
-xmlValue, err := m.Xml()      // marshal
- -Unmarshal XML from an `io.Reader` as a `Map` value, 'm': -
m, err := NewMapReader(xmlReader)         // repeated calls, as with an os.File Reader, will process stream
-m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded
- -Marshal `Map` value, 'm', to an XML Writer (`io.Writer`): -
err := m.XmlWriter(xmlWriter)
-raw, err := m.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter
- -Also, for prettified output: -
xmlValue, err := m.XmlIndent(prefix, indent, ...)
-err := m.XmlIndentWriter(xmlWriter, prefix, indent, ...)
-raw, err := m.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...)
- -Bulk process XML with error handling (note: handlers must return a boolean value): -
err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
-err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte))
- -Converting XML to JSON: see Examples for `NewMapXml` and `HandleXmlReader`. - -There are comparable functions and methods for JSON processing. - -Arbitrary structure values can be decoded to / encoded from `Map` values: -
m, err := NewMapStruct(structVal)
-err := m.Struct(structPointer)
- -

Extract / modify Map values

-To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON -or structure to a `Map` value, 'm', or cast a `map[string]interface{}` value to a `Map` value, 'm', then: -
paths := m.PathsForKey(key)
-path := m.PathForKeyShortest(key)
-values, err := m.ValuesForKey(key, subkeys)
-values, err := m.ValuesForPath(path, subkeys)
-count, err := m.UpdateValuesForPath(newVal, path, subkeys)
- -Get everything at once, irrespective of path depth: -
leafnodes := m.LeafNodes()
-leafvalues := m.LeafValues()
- -A new `Map` with whatever keys are desired can be created from the current `Map` and then encoded in XML -or JSON. (Note: keys can use dot-notation.) -
newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
-newXml := newMap.Xml()   // for example
-newJson := newMap.Json() // ditto
- -

Usage

- -The package is fairly well self-documented with examples. (http://godoc.org/github.com/clbanning/mxj) - -Also, the subdirectory "examples" contains a wide range of examples, several taken from golang-nuts discussions. - -

XML parsing conventions

- - - Attributes are parsed to `map[string]interface{}` values by prefixing a hyphen, `-`, - to the attribute label. (Unless overridden by `PrependAttrWithHyphen(false)`.) - - If the element is a simple element and has attributes, the element value - is given the key `#text` for its `map[string]interface{}` representation. (See - the 'atomFeedString.xml' test data, below.) - -

XML encoding conventions

- - - 'nil' `Map` values, which may represent 'null' JSON values, are encoded as ``. - NOTE: the operation is not symmetric as `` elements are decoded as `tag:""` `Map` values, - which, then, encode in JSON as `"tag":""` values. - -

Running "go test"

- -Because there are no guarantees on the sequence map elements are retrieved, the tests have been -written for visual verification in most cases. One advantage is that you can easily use the -output from running "go test" as examples of calling the various functions and methods. - -

Motivation

- -I make extensive use of JSON for messaging and typically unmarshal the messages into -`map[string]interface{}` variables. This is easily done using `json.Unmarshal` from the -standard Go libraries. Unfortunately, many legacy solutions use structured -XML messages; in those environments the applications would have to be refitted to -interoperate with my components. - -The better solution is to just provide an alternative HTTP handler that receives -XML messages and parses it into a `map[string]interface{}` variable and then reuse -all the JSON-based code. The Go `xml.Unmarshal()` function does not provide the same -option of unmarshaling XML messages into `map[string]interface{}` variables. So I wrote -a couple of small functions to fill this gap and released them as the x2j package. - -Over the next year and a half additional features were added, and the companion j2x -package was released to address XML encoding of arbitrary JSON and `map[string]interface{}` -values. As part of a refactoring of our production system and looking at how we had been -using the x2j and j2x packages we found that we rarely performed direct XML-to-JSON or -JSON-to_XML conversion and that working with the XML or JSON as `map[string]interface{}` -values was the primary value. Thus, everything was refactored into the mxj package. - diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/remove.go b/Godeps/_workspace/src/github.com/clbanning/mxj/remove.go deleted file mode 100644 index 8362ab17..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/remove.go +++ /dev/null @@ -1,37 +0,0 @@ -package mxj - -import "strings" - -// Removes the path. -func (mv Map) Remove(path string) error { - m := map[string]interface{}(mv) - return remove(m, path) -} - -func remove(m interface{}, path string) error { - val, err := prevValueByPath(m, path) - if err != nil { - return err - } - - lastKey := lastKey(path) - delete(val, lastKey) - - return nil -} - -// returns the last key of the path. -// lastKey("a.b.c") would had returned "c" -func lastKey(path string) string { - keys := strings.Split(path, ".") - key := keys[len(keys)-1] - return key -} - -// returns the path without the last key -// parentPath("a.b.c") whould had returned "a.b" -func parentPath(path string) string { - keys := strings.Split(path, ".") - parentPath := strings.Join(keys[0:len(keys)-1], ".") - return parentPath -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/remove_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/remove_test.go deleted file mode 100644 index 642d07ce..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/remove_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package mxj - -import ( - "testing" -) - -func TestRemove(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - }, - } - mv := Map(m) - err := mv.Remove("Div.Colour") - if err != nil { - t.Fatal(err) - } - if mv.Exists("Div.Colour") { - t.Fatal("removed key still remain") - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/rename.go b/Godeps/_workspace/src/github.com/clbanning/mxj/rename.go deleted file mode 100644 index 511d7b17..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/rename.go +++ /dev/null @@ -1,54 +0,0 @@ -package mxj - -import ( - "errors" - "strings" -) - -// RenameKey renames a key in a Map. -// It works only for nested maps. It doesn't work for cases when it buried in a list. -func (mv Map) RenameKey(path string, newName string) error { - if !mv.Exists(path) { - return errors.New("RenameKey: the path not found: " + path) - } - if mv.Exists(parentPath(path) + "." + newName) { - return errors.New("RenameKey: the key already exists: " + newName) - } - - m := map[string]interface{}(mv) - return renameKey(m, path, newName) -} - -func renameKey(m interface{}, path string, newName string) error { - val, err := prevValueByPath(m, path) - if err != nil { - return err - } - - oldName := lastKey(path) - val[newName] = val[oldName] - delete(val, oldName) - - return nil -} - -// returns a value which contains a last key in the path -// For example: prevValueByPath("a.b.c", {a{b{c: 3}}}) returns {c: 3} -func prevValueByPath(m interface{}, path string) (map[string]interface{}, error) { - keys := strings.Split(path, ".") - - switch mValue := m.(type) { - case map[string]interface{}: - for key, value := range mValue { - if key == keys[0] { - if len(keys) == 1 { - return mValue, nil - } else { - // keep looking for the full path to the key - return prevValueByPath(value, strings.Join(keys[1:], ".")) - } - } - } - } - return nil, errors.New("prevValueByPath: didn't find the path – " + path) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/rename_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/rename_test.go deleted file mode 100644 index d712c200..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/rename_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package mxj - -import ( - "testing" -) - -func TestRenameKey(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - "Width": "100%", - }, - } - mv := Map(m) - err := mv.RenameKey("Div.Colour", "Color") - if err != nil { - t.Fatal(err) - } - values, err := mv.ValuesForPath("Div.Color") - if len(values) != 1 { - t.Fatal("didn't add the new key") - } - if values[0] != "blue" { - t.Fatal("value is changed") - } - values, err = mv.ValuesForPath("Div.Colour") - if len(values) > 0 { - t.Fatal("didn't removed the old key") - } - - err = mv.RenameKey("not.existing.path", "newname") - if err == nil { - t.Fatal("should raise an error on a non existing path") - } - - err = mv.RenameKey("Div.Color", "Width") - if err == nil { - t.Fatal("should raise an error if the newName already exists") - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/seqnum_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/seqnum_test.go deleted file mode 100644 index 7b48a7ca..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/seqnum_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// seqnum.go - -package mxj - -import ( - "fmt" - "testing" -) - -var seqdata1 = []byte(` - - - - - `) - -var seqdata2 = []byte(` - - - - 1 - hello - true - - - `) - -func TestSeqNumHeader(t *testing.T) { - fmt.Println("\n---------------- seqnum_test.go ...\n") -} - -func TestSeqNum(t *testing.T) { - IncludeTagSeqNum(true) - - m, err := NewMapXml(seqdata1, Cast) - if err != nil { - t.Fatal(err) - } - fmt.Printf("m1: %#v\n", m) - j, _ := m.JsonIndent("", " ") - fmt.Println(string(j)) - - m, err = NewMapXml(seqdata2, Cast) - if err != nil { - t.Fatal(err) - } - fmt.Printf("m2: %#v\n", m) - j, _ = m.JsonIndent("", " ") - fmt.Println(string(j)) - - IncludeTagSeqNum(false) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/set.go b/Godeps/_workspace/src/github.com/clbanning/mxj/set.go deleted file mode 100644 index f937d36f..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/set.go +++ /dev/null @@ -1,23 +0,0 @@ -package mxj - -import ( - "strings" -) - -// Sets the value for the path -func (mv Map) SetValueForPath(value interface{}, path string) error { - pathAry := strings.Split(path, ".") - parentPathAry := pathAry[0 : len(pathAry)-1] - parentPath := strings.Join(parentPathAry, ".") - - val, err := mv.ValueForPath(parentPath) - if err != nil { - return err - } - - key := pathAry[len(pathAry)-1] - cVal := val.(map[string]interface{}) - cVal[key] = value - - return nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/set_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/set_test.go deleted file mode 100644 index 6d4d16ee..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/set_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package mxj - -import ( - "testing" -) - -func TestSetValueForPath(t *testing.T) { - m := map[string]interface{}{ - "Div": map[string]interface{}{ - "Colour": "blue", - "Font": map[string]interface{}{ - "Family": "sans", - }, - }, - } - mv := Map(m) - - // testing setting a new key - err := mv.SetValueForPath("big", "Div.Font.Size") - if err != nil { - t.Fatal(err) - } - val, err := mv.ValueForPathString("Div.Font.Size") - if err != nil { - t.Fatal(err) - } - if val != "big" { - t.Fatal("key's value hasn't changed") - } - - // testing setting a new value to en existing key - err = mv.SetValueForPath("red", "Div.Colour") - if err != nil { - t.Fatal(err) - } - val, err = mv.ValueForPathString("Div.Colour") - if err != nil { - t.Fatal(err) - } - if val != "red" { - t.Fatal("existig key's value hasn't changed") - } -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/struct.go b/Godeps/_workspace/src/github.com/clbanning/mxj/struct.go deleted file mode 100644 index 3bb2ef7c..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/struct.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -package mxj - -import ( - "encoding/json" - "errors" - "github.com/fatih/structs" - "reflect" -) - -// Create a new Map value from a structure. Error returned if argument is not a structure -// or if there is a json.Marshal or json.Unmarshal error. -// Only public structure fields are decoded in the Map value. Also, json.Marshal structure encoding rules -// are followed for decoding the structure fields. -func NewMapStruct(structVal interface{}) (Map, error) { - if !structs.IsStruct(structVal) { - return nil, errors.New("NewMapStruct() error: argument is not type Struct") - } - return structs.Map(structVal), nil -} - -// Marshal a map[string]interface{} into a structure referenced by 'structPtr'. Error returned -// if argument is not a pointer or if json.Unmarshal returns an error. -// json.Unmarshal structure encoding rules are followed to encode public structure fields. -func (mv Map) Struct(structPtr interface{}) error { - m := map[string]interface{}(mv) - j, err := json.Marshal(m) - if err != nil { - return err - } - - // should check that we're getting a pointer. - if reflect.ValueOf(structPtr).Kind() != reflect.Ptr { - return errors.New("mv.Struct() error: argument is not type Ptr") - } - return json.Unmarshal(j, structPtr) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/struct_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/struct_test.go deleted file mode 100644 index 799de778..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/struct_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package mxj - -import ( - "fmt" - "testing" -) - -func TestStructHeader(t *testing.T) { - fmt.Println("\n---------------- struct_test.go ...\n") -} - -func TestNewMapStruct(t *testing.T) { - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - private string - } - s := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "It's my party"} - - m, merr := NewMapStruct(s) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - - fmt.Printf("NewMapStruct, s: %#v\n", s) - fmt.Printf("NewMapStruct, m: %#v\n", m) - - m, merr = NewMapStruct(s) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - - fmt.Printf("NewMapStruct, s: %#v\n", s) - fmt.Printf("NewMapStruct, m: %#v\n", m) -} - -func TestNewMapStructError(t *testing.T) { - var s string - _, merr := NewMapStruct(s) - if merr == nil { - t.Fatal("NewMapStructError, merr is nil") - } - - fmt.Println("NewMapStructError, merr:", merr.Error()) -} - -func TestStruct(t *testing.T) { - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - private string - } - var s str - m := Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true, "private": "Somewhere over the rainbow"} - - mverr := m.Struct(&s) - if mverr != nil { - t.Fatal("mverr:", mverr.Error()) - } - - fmt.Printf("Struct, m: %#v\n", m) - fmt.Printf("Struct, s: %#v\n", s) -} - -func TestStructError(t *testing.T) { - type str struct { - IntVal int `json:"int"` - StrVal string `json:"str"` - FloatVal float64 `json:"float"` - BoolVal bool `json:"bool"` - } - var s str - mv := Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true} - - mverr := mv.Struct(s) - if mverr == nil { - t.Fatal("StructError, no error returned") - } - fmt.Println("StructError, mverr:", mverr.Error()) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues.go b/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues.go deleted file mode 100644 index fed54bc4..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// updatevalues.go - modify a value based on path and possibly sub-keys - -package mxj - -import ( - "fmt" - "strconv" - "strings" -) - -// Update value based on path and possible sub-key values. -// A count of the number of values changed and any error are returned. -// If the count == 0, then no path (and subkeys) matched. -// 'newVal' can be a Map or map[string]interface{} value with a single 'key' that is the key to be modified -// or a string value "key:value[:type]" where type is "bool" or "num" to cast the value. -// 'path' is dot-notation list of keys to traverse; last key in path can be newVal key -// NOTE: 'path' spec does not currently support indexed array references. -// 'subkeys' are "key:value[:type]" entries that must match for path node -// The subkey can be wildcarded - "key:*" - to require that it's there with some value. -// If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an -// exclusion critera - e.g., "!author:William T. Gaddis". -func (mv Map) UpdateValuesForPath(newVal interface{}, path string, subkeys ...string) (int, error) { - m := map[string]interface{}(mv) - - // extract the subkeys - var subKeyMap map[string]interface{} - if len(subkeys) > 0 { - var err error - subKeyMap, err = getSubKeyMap(subkeys...) - if err != nil { - return 0, err - } - } - - // extract key and value from newVal - var key string - var val interface{} - switch newVal.(type) { - case map[string]interface{}, Map: - switch newVal.(type) { // "fallthrough is not permitted in type switch" (Spec) - case Map: - newVal = newVal.(Map).Old() - } - if len(newVal.(map[string]interface{})) != 1 { - return 0, fmt.Errorf("newVal map can only have len == 1 - %+v", newVal) - } - for key, val = range newVal.(map[string]interface{}) { - } - case string: // split it as a key:value pair - ss := strings.Split(newVal.(string), ":") - n := len(ss) - if n < 2 || n > 3 { - return 0, fmt.Errorf("unknown newVal spec - %+v", newVal) - } - key = ss[0] - if n == 2 { - val = interface{}(ss[1]) - } else if n == 3 { - switch ss[2] { - case "bool", "boolean": - nv, err := strconv.ParseBool(ss[1]) - if err != nil { - return 0, fmt.Errorf("can't convert newVal to bool - %+v", newVal) - } - val = interface{}(nv) - case "num", "numeric", "float", "int": - nv, err := strconv.ParseFloat(ss[1], 64) - if err != nil { - return 0, fmt.Errorf("can't convert newVal to float64 - %+v", newVal) - } - val = interface{}(nv) - default: - return 0, fmt.Errorf("unknown type for newVal value - %+v", newVal) - } - } - default: - return 0, fmt.Errorf("invalid newVal type - %+v", newVal) - } - - // parse path - keys := strings.Split(path, ".") - - var count int - updateValuesForKeyPath(key, val, m, keys, subKeyMap, &count) - - return count, nil -} - -// navigate the path -func updateValuesForKeyPath(key string, value interface{}, m interface{}, keys []string, subkeys map[string]interface{}, cnt *int) { - // ----- at end node: looking at possible node to get 'key' ---- - if len(keys) == 1 { - updateValue(key, value, m, keys[0], subkeys, cnt) - return - } - - // ----- here we are navigating the path thru the penultimate node -------- - // key of interest is keys[0] - the next in the path - switch keys[0] { - case "*": // wildcard - scan all values - switch m.(type) { - case map[string]interface{}: - for _, v := range m.(map[string]interface{}) { - updateValuesForKeyPath(key, value, v, keys[1:], subkeys, cnt) - } - case []interface{}: - for _, v := range m.([]interface{}) { - switch v.(type) { - // flatten out a list of maps - keys are processed - case map[string]interface{}: - for _, vv := range v.(map[string]interface{}) { - updateValuesForKeyPath(key, value, vv, keys[1:], subkeys, cnt) - } - default: - updateValuesForKeyPath(key, value, v, keys[1:], subkeys, cnt) - } - } - } - default: // key - must be map[string]interface{} - switch m.(type) { - case map[string]interface{}: - if v, ok := m.(map[string]interface{})[keys[0]]; ok { - updateValuesForKeyPath(key, value, v, keys[1:], subkeys, cnt) - } - case []interface{}: // may be buried in list - for _, v := range m.([]interface{}) { - switch v.(type) { - case map[string]interface{}: - if vv, ok := v.(map[string]interface{})[keys[0]]; ok { - updateValuesForKeyPath(key, value, vv, keys[1:], subkeys, cnt) - } - } - } - } - } -} - -// change value if key and subkeys are present -func updateValue(key string, value interface{}, m interface{}, keys0 string, subkeys map[string]interface{}, cnt *int) { - // there are two possible options for the value of 'keys0': map[string]interface, []interface{} - // and 'key' is a key in the map or is a key in a map in a list. - switch m.(type) { - case map[string]interface{}: // gotta have the last key - if keys0 == "*" { - for k := range m.(map[string]interface{}) { - updateValue(key, value, m, k, subkeys, cnt) - } - return - } - endVal, _ := m.(map[string]interface{})[keys0] - - // if newV key is the end of path, replace the value for path-end - // may be []interface{} - means replace just an entry w/ subkeys - // otherwise replace the keys0 value if subkeys are there - // NOTE: this will replace the subkeys, also - if key == keys0 { - switch endVal.(type) { - case map[string]interface{}: - if ok := hasSubKeys(m, subkeys); ok { - (m.(map[string]interface{}))[keys0] = value - (*cnt)++ - } - case []interface{}: - // without subkeys can't select list member to modify - // so key:value spec is it ... - if len(subkeys) == 0 { - (m.(map[string]interface{}))[keys0] = value - (*cnt)++ - break - } - nv := make([]interface{}, 0) - var valmodified bool - for _, v := range endVal.([]interface{}) { - // check entry subkeys - if ok := hasSubKeys(v, subkeys); ok { - // replace v with value - nv = append(nv, value) - valmodified = true - (*cnt)++ - continue - } - nv = append(nv, v) - } - if valmodified { - (m.(map[string]interface{}))[keys0] = interface{}(nv) - } - default: // anything else is a strict replacement - if len(subkeys) == 0 { - (m.(map[string]interface{}))[keys0] = value - (*cnt)++ - } - } - return - } - - // so value is for an element of endVal - // if endVal is a map then 'key' must be there w/ subkeys - // if endVal is a list then 'key' must be in a list member w/ subkeys - switch endVal.(type) { - case map[string]interface{}: - if ok := hasSubKeys(endVal, subkeys); !ok { - return - } - if _, ok := (endVal.(map[string]interface{}))[key]; ok { - (endVal.(map[string]interface{}))[key] = value - (*cnt)++ - } - case []interface{}: // keys0 points to a list, check subkeys - for _, v := range endVal.([]interface{}) { - // got to be a map so we can replace value for 'key' - vv, vok := v.(map[string]interface{}) - if !vok { - continue - } - if _, ok := vv[key]; !ok { - continue - } - if !hasSubKeys(vv, subkeys) { - continue - } - vv[key] = value - (*cnt)++ - } - } - case []interface{}: // key may be in a list member - // don't need to handle keys0 == "*"; we're looking at everything, anyway. - for _, v := range m.([]interface{}) { - // only map values - we're looking for 'key' - mm, ok := v.(map[string]interface{}) - if !ok { - continue - } - if _, ok := mm[key]; !ok { - continue - } - if !hasSubKeys(mm, subkeys) { - continue - } - mm[key] = value - (*cnt)++ - } - } - - // return -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues_test.go deleted file mode 100644 index dca2da91..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/updatevalues_test.go +++ /dev/null @@ -1,187 +0,0 @@ -// modifyvalues_test.go - test keyvalues.go methods - -package mxj - -import ( - "fmt" - "testing" -) - -func TestUVHeader(t *testing.T) { - fmt.Println("\n---------------- updatevalues_test.go ...\n") -} - -func TestUpdateValuesForPath_Author(t *testing.T) { - m, merr := NewMapXml(doc1) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("m:", m) - - ss, _ := m.ValuesForPath("doc.books.book.author") - for _, v := range ss { - fmt.Println("v:", v) - } - fmt.Println("m.UpdateValuesForPath(\"author:NoName\", \"doc.books.book.author\")") - n, err := m.UpdateValuesForPath("author:NoName", "doc.books.book.author") - if err != nil { - t.Fatal("err:", err.Error()) - } - fmt.Println(n, "updates") - ss, _ = m.ValuesForPath("doc.books.book.author") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("m.UpdateValuesForPath(\"author:William Gadddis\", \"doc.books.book.author\", \"title:The Recognitions\")") - n, err = m.UpdateValuesForPath("author:William Gadddis", "doc.books.book.author", "title:The Recognitions") - o, _ := m.UpdateValuesForPath("author:Austin Tappen Wright", "doc.books.book", "title:Islandia") - p, _ := m.UpdateValuesForPath("author:John Hawkes", "doc.books.book", "title:The Beetle Leg") - q, _ := m.UpdateValuesForPath("author:T. E. Porter", "doc.books.book", "title:King's Day") - if err != nil { - t.Fatal("err:", err.Error()) - } - fmt.Println(n+o+p+q, "updates") - ss, _ = m.ValuesForPath("doc.books.book.author") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("m.UpdateValuesForPath(\"author:William T. Gaddis\", \"doc.books.book.*\", \"title:The Recognitions\")") - n, _ = m.UpdateValuesForPath("author:William T. Gaddis", "doc.books.book.*", "title:The Recognitions") - fmt.Println(n, "updates") - ss, _ = m.ValuesForPath("doc.books.book.author") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("m.UpdateValuesForPath(\"title:The Cannibal\", \"doc.books.book.title\", \"author:John Hawkes\")") - n, _ = m.UpdateValuesForPath("title:The Cannibal", "doc.books.book.title", "author:John Hawkes") - o, _ = m.UpdateValuesForPath("review:A novel on his experiences in WWII.", "doc.books.book.review", "title:The Cannibal") - fmt.Println(n+o, "updates") - ss, _ = m.ValuesForPath("doc.books.book") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("m.UpdateValuesForPath(\"books:\", \"doc.books\")") - n, _ = m.UpdateValuesForPath("books:", "doc.books") - fmt.Println(n, "updates") - fmt.Println("m:", m) - - fmt.Println("m.UpdateValuesForPath(mm, \"*\")") - mm, _ := NewMapXml(doc1) - n, err = m.UpdateValuesForPath(mm, "*") - if err != nil { - t.Fatal("err:", err.Error()) - } - fmt.Println(n, "updates") - fmt.Println("m:", m) - - // ---------------------- newDoc - var newDoc = []byte(`simple element`) - m, merr = NewMapXml(newDoc) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println("\nnewDoc:", string(newDoc)) - fmt.Println("m:", m) - fmt.Println("m.UpdateValuesForPath(\"#text:maybe not so simple element\", \"tag\")") - n, _ = m.UpdateValuesForPath("#text:maybe not so simple element", "tag") - fmt.Println("n:", n, "m:", m) - fmt.Println("m.UpdateValuesForPath(\"#text:simple element again\", \"*\")") - n, _ = m.UpdateValuesForPath("#text:simple element again", "*") - fmt.Println("n:", n, "m:", m) - - /* - fmt.Println("UpdateValuesForPath, doc.books.book, title:The Recognitions : NoBook") - n, err = m.UpdateValuesForPath("NoBook", "doc.books.book", "title:The Recognitions") - if err != nil { - t.Fatal("err:", err.Error()) - } - fmt.Println(n, "updates") - ss, _ = m.ValuesForPath("doc.books.book") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("UpdateValuesForPath, doc.books.book.title -seq=3: The Blood Oranges") - n, err = m.UpdateValuesForPath("The Blood Oranges", "doc.books.book.title", "-seq:3") - if err != nil { - t.Fatal("err:", err.Error()) - } - fmt.Println(n, "updates") - ss, _ = m.ValuesForPath("doc.books.book.title") - for _, v := range ss { - fmt.Println("v:", v) - } - */ -} - -var authorDoc = []byte(` - - - William Gaddis - - - The Recognitions - 1955 - A novel that changed the face of American literature. - - - JR - 1975 - Winner of National Book Award for Fiction. - - - - - John Hawkes - - - The Cannibal - 1949 - A novel on his experiences in WWII. - - - The Beetle Leg - 1951 - A lyrical novel about the construction of Ft. Peck Dam in Montana. - - - The Blood Oranges - 1970 - Where everyone wants to vacation. - - - -`) - -func TestAuthorDoc(t *testing.T) { - m, merr := NewMapXml(authorDoc) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - fmt.Println(m.StringIndent()) - - fmt.Println("m.UpdateValuesForPath(\"review:National Book Award winner.\", \"*.*.*.*\", \"title:JR\")") - n, _ := m.UpdateValuesForPath("review:National Book Award winner.", "*.*.*.*", "title:JR") - fmt.Println(n, "updates") - ss, _ := m.ValuesForPath("biblio.author", "name:William Gaddis") - for _, v := range ss { - fmt.Println("v:", v) - } - - fmt.Println("m.UpdateValuesForPath(newVal, path, oldVal)") - path := m.PathForKeyShortest("date") - v, _ := m.ValuesForPath(path) - var counter int - for _, vv := range v { - oldVal := "date:" + vv.(string) - newVal := "date:" + vv.(string) + ":num" - n, _ = m.UpdateValuesForPath(newVal, path, oldVal) - counter += n - } - fmt.Println(counter, "updates") - fmt.Println(m.StringIndent()) -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/x2j/x2j.go b/Godeps/_workspace/src/github.com/clbanning/mxj/x2j/x2j.go deleted file mode 100644 index 5891aa1d..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/x2j/x2j.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// x2j - For (mostly) backwards compatibility with legacy x2j package. -// Wrappers for end-to-end XML to JSON transformation and value manipulation. -package x2j - -import ( - . "github.com/clbanning/mxj" - "io" -) - -// FromXml() --> map[string]interface{} -func XmlToMap(xmlVal []byte) (map[string]interface{}, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return map[string]interface{}(m), nil -} - -// map[string]interface{} --> ToXml() -func MapToXml(m map[string]interface{}) ([]byte, error) { - return Map(m).Xml() -} - -// FromXml() --> ToJson(). -func XmlToJson(xmlVal []byte, safeEncoding ...bool) ([]byte, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.Json(safeEncoding...) -} - -// FromXml() --> ToJsonWriterRaw(). -func XmlToJsonWriter(xmlVal []byte, jsonWriter io.Writer, safeEncoding ...bool) ([]byte, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.JsonWriterRaw(jsonWriter, safeEncoding...) -} - -// FromXmlReaderRaw() --> ToJson(). -func XmlReaderToJson(xmlReader io.Reader, safeEncoding ...bool) ([]byte, []byte, error) { - m, xraw, err := NewMapXmlReaderRaw(xmlReader) - if err != nil { - return xraw, nil, err - } - j, jerr := m.Json(safeEncoding...) - return xraw, j, jerr -} - -// FromXmlReader() --> ToJsonWriter(). Handy for bulk transformation of documents. -func XmlReaderToJsonWriter(xmlReader io.Reader, jsonWriter io.Writer, safeEncoding ...bool) ([]byte, []byte, error) { - m, xraw, err := NewMapXmlReaderRaw(xmlReader) - if err != nil { - return xraw, nil, err - } - jraw, jerr := m.JsonWriterRaw(jsonWriter, safeEncoding...) - return xraw, jraw, jerr -} - -// XML wrappers for Map methods implementing tag path and value functions. - -// Wrap PathsForKey for XML. -func XmlPathsForTag(xmlVal []byte, tag string) ([]string, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - paths := m.PathsForKey(tag) - return paths, nil -} - -// Wrap PathForKeyShortest for XML. -func XmlPathForTagShortest(xmlVal []byte, tag string) (string, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return "", err - } - path := m.PathForKeyShortest(tag) - return path, nil -} - -// Wrap ValuesForKey for XML. -// 'attrs' are key:value pairs for attributes, where key is attribute label prepended with a hypen, '-'. -func XmlValuesForTag(xmlVal []byte, tag string, attrs ...string) ([]interface{}, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.ValuesForKey(tag, attrs...) -} - -// Wrap ValuesForPath for XML. -// 'attrs' are key:value pairs for attributes, where key is attribute label prepended with a hypen, '-'. -func XmlValuesForPath(xmlVal []byte, path string, attrs ...string) ([]interface{}, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.ValuesForPath(path, attrs...) -} - -// Wrap UpdateValuesForPath for XML -// 'xmlVal' is XML value -// 'newTagValue' is the value to replace an existing value at the end of 'path' -// 'path' is the dot-notation path with the tag whose value is to be replaced at the end -// (can include wildcard character, '*') -// 'subkeys' are key:value pairs of tag:values that must match for the tag -func XmlUpdateValsForPath(xmlVal []byte, newTagValue interface{}, path string, subkeys ...string) ([]byte, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - _, err = m.UpdateValuesForPath(newTagValue, path, subkeys...) - if err != nil { - return nil, err - } - return m.Xml() -} - -// Wrap NewMap for XML and return as XML -// 'xmlVal' is an XML value -// 'tagpairs' are "oldTag:newTag" values that conform to 'keypairs' in (Map)NewMap. -func XmlNewXml(xmlVal []byte, tagpairs ...string) ([]byte, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - n, err := m.NewMap(tagpairs...) - if err != nil { - return nil, err - } - return n.Xml() -} - -// Wrap NewMap for XML and return as JSON -// 'xmlVal' is an XML value -// 'tagpairs' are "oldTag:newTag" values that conform to 'keypairs' in (Map)NewMap. -func XmlNewJson(xmlVal []byte, tagpairs ...string) ([]byte, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - n, err := m.NewMap(tagpairs...) - if err != nil { - return nil, err - } - return n.Json() -} - -// Wrap LeafNodes for XML. -// 'xmlVal' is an XML value -func XmlLeafNodes(xmlVal []byte) ([]LeafNode, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.LeafNodes(), nil -} - -// Wrap LeafValues for XML. -// 'xmlVal' is an XML value -func XmlLeafValues(xmlVal []byte) ([]interface{}, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.LeafValues(), nil -} - -// Wrap LeafPath for XML. -// 'xmlVal' is an XML value -func XmlLeafPath(xmlVal []byte) ([]string, error) { - m, err := NewMapXml(xmlVal) - if err != nil { - return nil, err - } - return m.LeafPaths(), nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/xml.go b/Godeps/_workspace/src/github.com/clbanning/mxj/xml.go deleted file mode 100644 index 691bc021..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/xml.go +++ /dev/null @@ -1,838 +0,0 @@ -// Copyright 2012-2014 Charles Banning. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file - -// xml.go - basically the core of X2j for map[string]interface{} values. -// NewMapXml, NewMapXmlReader, mv.Xml, mv.XmlWriter -// see x2j and j2x for wrappers to provide end-to-end transformation of XML and JSON messages. - -package mxj - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "regexp" - "strconv" - "strings" - "time" -) - -// ------------------- NewMapXml & NewMapXmlReader ... from x2j2 ------------------------- - -// If XmlCharsetReader != nil, it will be used to decode the XML, if required. -// import ( -// charset "code.google.com/p/go-charset/charset" -// github.com/clbanning/mxj -// ) -// ... -// mxj.XmlCharsetReader = charset.NewReader -// m, merr := mxj.NewMapXml(xmlValue) -var XmlCharsetReader func(charset string, input io.Reader) (io.Reader, error) - -// NewMapXml - convert a XML doc into a Map -// (This is analogous to unmarshalling a JSON string to map[string]interface{} using json.Unmarshal().) -// If the optional argument 'cast' is 'true', then values will be converted to boolean or float64 if possible. -// -// Converting XML to JSON is a simple as: -// ... -// mapVal, merr := mxj.NewMapXml(xmlVal) -// if merr != nil { -// // handle error -// } -// jsonVal, jerr := mapVal.Json() -// if jerr != nil { -// // handle error -// } -func NewMapXml(xmlVal []byte, cast ...bool) (Map, error) { - var r bool - if len(cast) == 1 { - r = cast[0] - } - n, err := xmlToTree(xmlVal) - if err != nil { - return nil, err - } - - m := make(map[string]interface{}, 0) - m[n.key] = n.treeToMap(r) - - return m, nil -} - -// Get next XML doc from an io.Reader as a Map value. Returns Map value. -func NewMapXmlReader(xmlReader io.Reader, cast ...bool) (Map, error) { - var r bool - if len(cast) == 1 { - r = cast[0] - } - - // build the node tree - n, err := xmlReaderToTree(xmlReader) - if err != nil { - return nil, err - } - - // create the Map value - m := make(map[string]interface{}) - m[n.key] = n.treeToMap(r) - - return m, nil -} - -// XmlWriterBufSize - set the size of io.Writer for the TeeReader used by NewMapXmlReaderRaw() -// and HandleXmlReaderRaw(). This reduces repeated memory allocations and copy() calls in most cases. -var XmlWriterBufSize int = 256 - -// Get next XML doc from an io.Reader as a Map value. Returns Map value and slice with the raw XML. -// NOTES: 1. Due to the implementation of xml.Decoder, the raw XML off the reader is buffered to []byte -// using a ByteReader. If the io.Reader is an os.File, there may be significant performance impact. -// See the examples - getmetrics1.go through getmetrics4.go - for comparative use cases on a large -// data set. If the io.Reader is wrapping a []byte value in-memory, however, such as http.Request.Body -// you CAN use it to efficiently unmarshal a XML doc and retrieve the raw XML in a single call. -// 2. The 'raw' return value may be larger than the XML text value. To log it, cast it to a string. -func NewMapXmlReaderRaw(xmlReader io.Reader, cast ...bool) (Map, []byte, error) { - var r bool - if len(cast) == 1 { - r = cast[0] - } - // create TeeReader so we can retrieve raw XML - buf := make([]byte, XmlWriterBufSize) - wb := bytes.NewBuffer(buf) - trdr := myTeeReader(xmlReader, wb) // see code at EOF - - // build the node tree - n, err := xmlReaderToTree(trdr) - - // retrieve the raw XML that was decoded - b := make([]byte, wb.Len()) - _, _ = wb.Read(b) - - if err != nil { - return nil, b, err - } - - // create the Map value - m := make(map[string]interface{}) - m[n.key] = n.treeToMap(r) - - return m, b, nil -} - -// xmlReaderToTree() - parse a XML io.Reader to a tree of nodes -func xmlReaderToTree(rdr io.Reader) (*node, error) { - // parse the Reader - p := xml.NewDecoder(rdr) - p.CharsetReader = XmlCharsetReader - return xmlToTreeParser("", nil, p) -} - -// for building the parse tree -type node struct { - dup bool // is member of a list - attr bool // is an attribute - key string // XML tag - val string // element value - nodes []*node -} - -// xmlToTree - convert a XML doc into a tree of nodes. -func xmlToTree(doc []byte) (*node, error) { - // xml.Decoder doesn't properly handle whitespace in some doc - // see songTextString.xml test case ... - reg, _ := regexp.Compile("[ \t\n\r]*<") - doc = reg.ReplaceAll(doc, []byte("<")) - - b := bytes.NewReader(doc) - p := xml.NewDecoder(b) - p.CharsetReader = XmlCharsetReader - n, berr := xmlToTreeParser("", nil, p) - if berr != nil { - return nil, berr - } - - return n, nil -} - -// we allow people to drop hyphen when unmarshaling the XML doc. -var useHyphen bool = true - -// PrependAttrWithHyphen. Prepend attribute tags with a hyphen. -// Default is 'true'. -// Note: -// If 'false', unmarshaling and marshaling is not symmetric. Attributes will be -// marshal'd as attr and may be part of a list. -func PrependAttrWithHyphen(v bool) { - useHyphen = v -} - -// Include sequence id with inner tags. - per Sean Murphy, murphysean84@gmail.com. -var includeTagSeqNum bool - -// IncludeTagSeqNum - include a "_seq":N key:value pair with each inner tag, denoting -// its position when parsed. E.g., -/* - - - - - hello - - - parses as: - - { - Obj:{ - "-c":"la", - "-h":"da", - "-x":"dee", - "intObj":[ - { - "-id"="3", - "_seq":"0" // if mxj.Cast is passed, then: "_seq":0 - }, - { - "-id"="2", - "_seq":"2" - }], - "intObj1":{ - "-id":"1", - "_seq":"1" - }, - "StrObj":{ - "#text":"hello", // simple element value gets "#text" tag - "_seq":"3" - } - } - } -*/ -func IncludeTagSeqNum(b bool) { - includeTagSeqNum = b -} - -// xmlToTreeParser - load a 'clean' XML doc into a tree of *node. -func xmlToTreeParser(skey string, a []xml.Attr, p *xml.Decoder) (*node, error) { - n := new(node) - n.nodes = make([]*node, 0) - var seq int // for includeTagSeqNum - - if skey != "" { - n.key = skey - if len(a) > 0 { - for _, v := range a { - na := new(node) - na.attr = true - if useHyphen { - na.key = `-` + v.Name.Local - } else { - na.key = v.Name.Local - } - na.val = v.Value - n.nodes = append(n.nodes, na) - } - } - } - for { - t, err := p.Token() - if err != nil { - if err != io.EOF { - return nil, errors.New("xml.Decoder.Token() - " + err.Error()) - } - return nil, err - } - switch t.(type) { - case xml.StartElement: - tt := t.(xml.StartElement) - // handle root - if n.key == "" { - n.key = tt.Name.Local - if len(tt.Attr) > 0 { - for _, v := range tt.Attr { - na := new(node) - na.attr = true - if useHyphen { - na.key = `-` + v.Name.Local - } else { - na.key = v.Name.Local - } - na.val = v.Value - n.nodes = append(n.nodes, na) - } - } - } else { - nn, nnerr := xmlToTreeParser(tt.Name.Local, tt.Attr, p) - if nnerr != nil { - return nil, nnerr - } - n.nodes = append(n.nodes, nn) - if includeTagSeqNum { // 2014.11.09 - sn := &node{false, false, "_seq", strconv.Itoa(seq), nil} - nn.nodes = append(nn.nodes, sn) - seq++ - } - } - case xml.EndElement: - // scan n.nodes for duplicate n.key values - n.markDuplicateKeys() - return n, nil - case xml.CharData: - tt := string(t.(xml.CharData)) - // clean up possible noise - tt = strings.Trim(tt, "\t\r\b\n ") - if len(n.nodes) > 0 && len(tt) > 0 { - // if len(n.nodes) > 0 { - nn := new(node) - nn.key = "#text" - nn.val = tt - n.nodes = append(n.nodes, nn) - } else { - n.val = tt - } - if includeTagSeqNum { // 2014.11.09 - if len(n.nodes) == 0 { // treat like a simple element with attributes - nn := new(node) - nn.key = "#text" - nn.val = tt - n.nodes = append(n.nodes, nn) - } - sn := &node{false, false, "_seq", strconv.Itoa(seq), nil} - n.nodes = append(n.nodes, sn) - seq++ - } - default: - // noop - } - } - // Logically we can't get here, but provide an error message anyway. - return nil, fmt.Errorf("Unknown parse error in xmlToTree() for: %s", n.key) -} - -// (*node)markDuplicateKeys - set node.dup flag for loading map[string]interface{}. -func (n *node) markDuplicateKeys() { - l := len(n.nodes) - for i := 0; i < l; i++ { - if n.nodes[i].dup { - continue - } - for j := i + 1; j < l; j++ { - if n.nodes[i].key == n.nodes[j].key { - n.nodes[i].dup = true - n.nodes[j].dup = true - } - } - } -} - -// (*node)treeToMap - convert a tree of nodes into a map[string]interface{}. -// (Parses to map that is structurally the same as from json.Unmarshal().) -// Note: root is not instantiated; call with: "m[n.key] = n.treeToMap(cast)". -func (n *node) treeToMap(r bool) interface{} { - if len(n.nodes) == 0 { - return cast(n.val, r) - } - - m := make(map[string]interface{}, 0) - for _, v := range n.nodes { - // 2014.11.9 - may have to back out - if includeTagSeqNum { - if len(v.nodes) == 1 { - m[v.key] = cast(v.val, r) - continue - } - } - - // just a value - if !v.dup && len(v.nodes) == 0 { - m[v.key] = cast(v.val, r) - continue - } - // a list of values - if v.dup { - var a []interface{} - if vv, ok := m[v.key]; ok { - a = vv.([]interface{}) - } else { - a = make([]interface{}, 0) - } - a = append(a, v.treeToMap(r)) - m[v.key] = interface{}(a) - continue - } - - // it's a unique key - m[v.key] = v.treeToMap(r) - } - - return interface{}(m) -} - -// cast - try to cast string values to bool or float64 -func cast(s string, r bool) interface{} { - if r { - // handle numeric strings ahead of boolean - if f, err := strconv.ParseFloat(s, 64); err == nil { - return interface{}(f) - } - // ParseBool treats "1"==true & "0"==false - // but be more strick - only allow TRUE, True, true, FALSE, False, false - if s != "t" && s != "T" && s != "f" && s != "F" { - if b, err := strconv.ParseBool(s); err == nil { - return interface{}(b) - } - } - } - return interface{}(s) -} - -// ------------------ END: NewMapXml & NewMapXmlReader ------------------------- - -// ------------------ mv.Xml & mv.XmlWriter - from j2x ------------------------ - -const ( - DefaultRootTag = "doc" -) - -var useGoXmlEmptyElemSyntax bool - -// XmlGoEmptyElemSyntax() - rather than . -// Go's encoding/xml package marshals empty XML elements as . By default this package -// encodes empty elements as . If you're marshaling Map values that include structures -// (which are passed to xml.Marshal for encoding), this will let you conform to the standard package. -// -// Alternatively, you can replace the encoding/xml/marshal.go file in the standard libary with the -// patched version in the "xml_marshal" folder in this package. Then use xml.SetUseNullEndTag(true) -// to have all XML encoding use for empty elements. -func XmlGoEmptyElemSyntax() { - useGoXmlEmptyElemSyntax = true -} - -// XmlDefaultEmptyElemSyntax() - rather than . -// Return XML encoding for empty elements to the default package setting. -// Reverses effect of XmlGoEmptyElemSyntax(). -func XmlDefaultEmptyElemSyntax() { - useGoXmlEmptyElemSyntax = false -} - -// Encode a Map as XML. The companion of NewMapXml(). -// The following rules apply. -// - The key label "#text" is treated as the value for a simple element with attributes. -// - Map keys that begin with a hyphen, '-', are interpreted as attributes. -// It is an error if the attribute doesn't have a []byte, string, number, or boolean value. -// - Map value type encoding: -// > string, bool, float64, int, int32, int64, float32: per "%v" formating -// > []bool, []uint8: by casting to string -// > structures, etc.: handed to xml.Marshal() - if there is an error, the element -// value is "UNKNOWN" -// - Elements with only attribute values or are null are terminated using "/>". -// - If len(mv) == 1 and no rootTag is provided, then the map key is used as the root tag, possible. -// Thus, `{ "key":"value" }` encodes as "value". -// - To encode empty elements in a syntax consistent with encoding/xml call UseGoXmlEmptyElementSyntax(). -func (mv Map) Xml(rootTag ...string) ([]byte, error) { - m := map[string]interface{}(mv) - var err error - s := new(string) - p := new(pretty) // just a stub - - if len(m) == 1 && len(rootTag) == 0 { - for key, value := range m { - // if it an array, see if all values are map[string]interface{} - // we force a new root tag if we'll end up with no key:value in the list - // so: key:[string_val, bool:true] --> string_valtrue - switch value.(type) { - case []interface{}: - for _, v := range value.([]interface{}) { - switch v.(type) { - case map[string]interface{}: // noop - default: // anything else - err = mapToXmlIndent(false, s, DefaultRootTag, m, p) - goto done - } - } - } - err = mapToXmlIndent(false, s, key, value, p) - } - } else if len(rootTag) == 1 { - err = mapToXmlIndent(false, s, rootTag[0], m, p) - } else { - err = mapToXmlIndent(false, s, DefaultRootTag, m, p) - } -done: - return []byte(*s), err -} - -// The following implementation is provided only for symmetry with NewMapXmlReader[Raw] -// The names will also provide a key for the number of return arguments. - -// Writes the Map as XML on the Writer. -// See Xml() for encoding rules. -func (mv Map) XmlWriter(xmlWriter io.Writer, rootTag ...string) error { - x, err := mv.Xml(rootTag...) - if err != nil { - return err - } - - _, err = xmlWriter.Write(x) - return err -} - -// Writes the Map as XML on the Writer. []byte is the raw XML that was written. -// See Xml() for encoding rules. -func (mv Map) XmlWriterRaw(xmlWriter io.Writer, rootTag ...string) ([]byte, error) { - x, err := mv.Xml(rootTag...) - if err != nil { - return x, err - } - - _, err = xmlWriter.Write(x) - return x, err -} - -// Writes the Map as pretty XML on the Writer. -// See Xml() for encoding rules. -func (mv Map) XmlIndentWriter(xmlWriter io.Writer, prefix, indent string, rootTag ...string) error { - x, err := mv.XmlIndent(prefix, indent, rootTag...) - if err != nil { - return err - } - - _, err = xmlWriter.Write(x) - return err -} - -// Writes the Map as pretty XML on the Writer. []byte is the raw XML that was written. -// See Xml() for encoding rules. -func (mv Map) XmlIndentWriterRaw(xmlWriter io.Writer, prefix, indent string, rootTag ...string) ([]byte, error) { - x, err := mv.XmlIndent(prefix, indent, rootTag...) - if err != nil { - return x, err - } - - _, err = xmlWriter.Write(x) - return x, err -} - -// -------------------- END: mv.Xml & mv.XmlWriter ------------------------------- - -// -------------- Handle XML stream by processing Map value -------------------- - -// Default poll delay to keep Handler from spinning on an open stream -// like sitting on os.Stdin waiting for imput. -var xhandlerPollInterval = time.Duration(1e6) - -// Bulk process XML using handlers that process a Map value. -// 'rdr' is an io.Reader for XML (stream) -// 'mapHandler' is the Map processor. Return of 'false' stops io.Reader processing. -// 'errHandler' is the error processor. Return of 'false' stops io.Reader processing and returns the error. -// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized. -// This means that you can stop reading the file on error or after processing a particular message. -// To have reading and handling run concurrently, pass argument to a go routine in handler and return 'true'. -func HandleXmlReader(xmlReader io.Reader, mapHandler func(Map) bool, errHandler func(error) bool) error { - var n int - for { - m, merr := NewMapXmlReader(xmlReader) - n++ - - // handle error condition with errhandler - if merr != nil && merr != io.EOF { - merr = fmt.Errorf("[xmlReader: %d] %s", n, merr.Error()) - if ok := errHandler(merr); !ok { - // caused reader termination - return merr - } - continue - } - - // pass to maphandler - if len(m) != 0 { - if ok := mapHandler(m); !ok { - break - } - } else if merr != io.EOF { - <-time.After(xhandlerPollInterval) - } - - if merr == io.EOF { - break - } - } - return nil -} - -// Bulk process XML using handlers that process a Map value and the raw XML. -// 'rdr' is an io.Reader for XML (stream) -// 'mapHandler' is the Map and raw XML - []byte - processor. Return of 'false' stops io.Reader processing. -// 'errHandler' is the error and raw XML processor. Return of 'false' stops io.Reader processing and returns the error. -// Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized. -// This means that you can stop reading the file on error or after processing a particular message. -// To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return 'true'. -// See NewMapXmlReaderRaw for comment on performance associated with retrieving raw XML from a Reader. -func HandleXmlReaderRaw(xmlReader io.Reader, mapHandler func(Map, []byte) bool, errHandler func(error, []byte) bool) error { - var n int - for { - m, raw, merr := NewMapXmlReaderRaw(xmlReader) - n++ - - // handle error condition with errhandler - if merr != nil && merr != io.EOF { - merr = fmt.Errorf("[xmlReader: %d] %s", n, merr.Error()) - if ok := errHandler(merr, raw); !ok { - // caused reader termination - return merr - } - continue - } - - // pass to maphandler - if len(m) != 0 { - if ok := mapHandler(m, raw); !ok { - break - } - } else if merr != io.EOF { - <-time.After(xhandlerPollInterval) - } - - if merr == io.EOF { - break - } - } - return nil -} - -// ----------------- END: Handle XML stream by processing Map value -------------- - -// -------- a hack of io.TeeReader ... need one that's an io.ByteReader for xml.NewDecoder() ---------- - -// This is a clone of io.TeeReader with the additional method t.ReadByte(). -// Thus, this TeeReader is also an io.ByteReader. -// This is necessary because xml.NewDecoder uses a ByteReader not a Reader. It appears to have been written -// with bufio.Reader or bytes.Reader in mind ... not a generic io.Reader, which doesn't have to have ReadByte().. -// If NewDecoder is passed a Reader that does not satisfy ByteReader() it wraps the Reader with -// bufio.NewReader and uses ReadByte rather than Read that runs the TeeReader pipe logic. - -type teeReader struct { - r io.Reader - w io.Writer - b []byte -} - -func myTeeReader(r io.Reader, w io.Writer) io.Reader { - b := make([]byte, 1) - return &teeReader{r, w, b} -} - -// need for io.Reader - but we don't use it ... -func (t *teeReader) Read(p []byte) (n int, err error) { - return 0, nil -} - -func (t *teeReader) ReadByte() (c byte, err error) { - n, err := t.r.Read(t.b) - if n > 0 { - if _, err := t.w.Write(t.b[:1]); err != nil { - return t.b[0], err - } - } - return t.b[0], err -} - -// ----------------------- END: io.TeeReader hack ----------------------------------- - -// ---------------------- XmlIndent - from j2x package ---------------------------- - -// Encode a map[string]interface{} as a pretty XML string. -// See Xml for encoding rules. -func (mv Map) XmlIndent(prefix, indent string, rootTag ...string) ([]byte, error) { - m := map[string]interface{}(mv) - - var err error - s := new(string) - p := new(pretty) - p.indent = indent - p.padding = prefix - - if len(m) == 1 && len(rootTag) == 0 { - // this can extract the key for the single map element - // use it if it isn't a key for a list - for key, value := range m { - if _, ok := value.([]interface{}); ok { - err = mapToXmlIndent(true, s, DefaultRootTag, m, p) - } else { - err = mapToXmlIndent(true, s, key, value, p) - } - } - } else if len(rootTag) == 1 { - err = mapToXmlIndent(true, s, rootTag[0], m, p) - } else { - err = mapToXmlIndent(true, s, DefaultRootTag, m, p) - } - return []byte(*s), err -} - -type pretty struct { - indent string - cnt int - padding string - mapDepth int - start int -} - -func (p *pretty) Indent() { - p.padding += p.indent - p.cnt++ -} - -func (p *pretty) Outdent() { - if p.cnt > 0 { - p.padding = p.padding[:len(p.padding)-len(p.indent)] - p.cnt-- - } -} - -// where the work actually happens -// returns an error if an attribute is not atomic -func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp *pretty) error { - var endTag bool - var isSimple bool - p := &pretty{pp.indent, pp.cnt, pp.padding, pp.mapDepth, pp.start} - - switch value.(type) { - case map[string]interface{}, []byte, string, float64, bool, int, int32, int64, float32: - if doIndent { - *s += p.padding - } - *s += `<` + key - } - switch value.(type) { - case map[string]interface{}: - vv := value.(map[string]interface{}) - lenvv := len(vv) - // scan out attributes - keys have prepended hyphen, '-' - var cntAttr int - for k, v := range vv { - if k[:1] == "-" { - switch v.(type) { - case string, float64, bool, int, int32, int64, float32: - *s += ` ` + k[1:] + `="` + fmt.Sprintf("%v", v) + `"` - cntAttr++ - case []byte: // allow standard xml pkg []byte transform, as below - *s += ` ` + k[1:] + `="` + fmt.Sprintf("%v", string(v.([]byte))) + `"` - cntAttr++ - default: - return fmt.Errorf("invalid attribute value for: %s", k) - } - } - } - // only attributes? - if cntAttr == lenvv { - break - } - // simple element? Note: '#text" is an invalid XML tag. - if v, ok := vv["#text"]; ok { - if cntAttr+1 < lenvv { - return errors.New("#text key occurs with other non-attribute keys") - } - *s += ">" + fmt.Sprintf("%v", v) - endTag = true - break - } - // close tag with possible attributes - *s += ">" - if doIndent { - *s += "\n" - } - // something more complex - p.mapDepth++ - var i int - for k, v := range vv { - if k[:1] == "-" { - continue - } - switch v.(type) { - case []interface{}: - default: - if i == 0 && doIndent { - p.Indent() - } - } - i++ - mapToXmlIndent(doIndent, s, k, v, p) - switch v.(type) { - case []interface{}: // handled in []interface{} case - default: - if doIndent { - p.Outdent() - } - } - i-- - } - p.mapDepth-- - endTag = true - case []interface{}: - for _, v := range value.([]interface{}) { - if doIndent { - p.Indent() - } - mapToXmlIndent(doIndent, s, key, v, p) - if doIndent { - p.Outdent() - } - } - return nil - case nil: - // terminate the tag - *s += "<" + key - break - default: // handle anything - even goofy stuff - switch value.(type) { - case string, float64, bool, int, int32, int64, float32: - *s += ">" + fmt.Sprintf("%v", value) - case []byte: // NOTE: byte is just an alias for uint8 - // similar to how xml.Marshal handles []byte structure members - *s += ">" + string(value.([]byte)) - default: - var v []byte - var err error - if doIndent { - v, err = xml.MarshalIndent(value, p.padding, p.indent) - } else { - v, err = xml.Marshal(value) - } - if err != nil { - *s += ">UNKNOWN" - } else { - *s += string(v) - } - } - isSimple = true - endTag = true - } - - if endTag { - if doIndent { - if !isSimple { - // if p.mapDepth == 0 { - // p.Outdent() - // } - *s += p.padding - } - } - switch value.(type) { - case map[string]interface{}, []byte, string, float64, bool, int, int32, int64, float32: - *s += `" - } - } else if useGoXmlEmptyElemSyntax { - *s += ">" - } else { - *s += "/>" - } - if doIndent { - if p.cnt > p.start { - *s += "\n" - } - p.Outdent() - } - - return nil -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/README b/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/README deleted file mode 100644 index ca36c45b..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/README +++ /dev/null @@ -1,26 +0,0 @@ -The mxj package terminates empty elements using '/>' rather than ''. - -The Xml(), XmlIndent(), XmlWriter() marshals Map values that can have structures or any other Go type -that xml.Marshal() can encode. If you want to have xml.Marshal() encode empty elements in a manner -consist with maputil, then you need to hack the src/pkg/encoding/xml/marshal.go file to support that -convention. - -The marshal.go.v1_2 file in this repo does that for Go v1.2; use it in place of the standard library -marshal.go file. - -The example_test.go.v1_2 file extends the package example_test.go file in the src/pkg/encoding/xml -directory to provide an example of the SetUseNullEndTag() function that you'll see in the new godoc -documentation for encoding/xml. xml.SetUseNullEndTag(true) causes xml.Marshal() to encode empty XML -elements as , just like this package. - -With the new marshal.go, you can then force all marshaling that uses encoding/xml to use mxj's -syntax rather than the Go standard syntax. - -NOTE: -If you install this patch then only use either - - - xml.SetUseNullEndTag() -or - - mxj.XmlGoEmptyElemSyntax() - -to have consistent encoding of empty XML elements. diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/example_test.go.v1_2 b/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/example_test.go.v1_2 deleted file mode 100644 index 2e035a43..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/example_test.go.v1_2 +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package xml_test - -import ( - "encoding/xml" - "fmt" - "os" -) - -func ExampleMarshalIndent() { - type Address struct { - City, State string - } - type Person struct { - XMLName xml.Name `xml:"person"` - Id int `xml:"id,attr"` - FirstName string `xml:"name>first"` - LastName string `xml:"name>last"` - Age int `xml:"age"` - Height float32 `xml:"height,omitempty"` - Married bool - Address - Comment string `xml:",comment"` - } - - v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} - v.Comment = " Need more details. " - v.Address = Address{"Hanga Roa", "Easter Island"} - - output, err := xml.MarshalIndent(v, " ", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - - os.Stdout.Write(output) - // Output: - // - // - // John - // Doe - // - // 42 - // false - // Hanga Roa - // Easter Island - // - // -} - -func ExampleEncoder() { - type Address struct { - City, State string - } - type Person struct { - XMLName xml.Name `xml:"person"` - Id int `xml:"id,attr"` - FirstName string `xml:"name>first"` - LastName string `xml:"name>last"` - Age int `xml:"age"` - Height float32 `xml:"height,omitempty"` - Married bool - Address - Comment string `xml:",comment"` - } - - v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} - v.Comment = " Need more details. " - v.Address = Address{"Hanga Roa", "Easter Island"} - - enc := xml.NewEncoder(os.Stdout) - enc.Indent(" ", " ") - if err := enc.Encode(v); err != nil { - fmt.Printf("error: %v\n", err) - } - - // Output: - // - // - // John - // Doe - // - // 42 - // false - // Hanga Roa - // Easter Island - // - // -} - -// This example demonstrates unmarshaling an XML excerpt into a value with -// some preset fields. Note that the Phone field isn't modified and that -// the XML element is ignored. Also, the Groups field is assigned -// considering the element path provided in its tag. -func ExampleUnmarshal() { - type Email struct { - Where string `xml:"where,attr"` - Addr string - } - type Address struct { - City, State string - } - type Result struct { - XMLName xml.Name `xml:"Person"` - Name string `xml:"FullName"` - Phone string - Email []Email - Groups []string `xml:"Group>Value"` - Address - } - v := Result{Name: "none", Phone: "none"} - - data := ` - - Grace R. Emlin - Example Inc. - - gre@example.com - - - gre@work.com - - - Friends - Squash - - Hanga Roa - Easter Island - - ` - err := xml.Unmarshal([]byte(data), &v) - if err != nil { - fmt.Printf("error: %v", err) - return - } - fmt.Printf("XMLName: %#v\n", v.XMLName) - fmt.Printf("Name: %q\n", v.Name) - fmt.Printf("Phone: %q\n", v.Phone) - fmt.Printf("Email: %v\n", v.Email) - fmt.Printf("Groups: %v\n", v.Groups) - fmt.Printf("Address: %v\n", v.Address) - // Output: - // XMLName: xml.Name{Space:"", Local:"Person"} - // Name: "Grace R. Emlin" - // Phone: "none" - // Email: [{home gre@example.com} {work gre@work.com}] - // Groups: [Friends Squash] - // Address: {Hanga Roa Easter Island} -} - -// This example demonstrates how SetUseNullEndTag changes the end tag syntax for Marshal. -func ExampleSetUseNullEndTag() { - type NullValStruct struct { - I int - B []byte - S string - } - s := new(NullValStruct) - - v, err := xml.Marshal(s) - if err != nil { - fmt.Println("err:", err.Error()) - } else { - fmt.Println("s:", string(v)) - } - - xml.SetUseNullEndTag(true) - v, err = xml.Marshal(s) - if err != nil { - fmt.Println("err:", err.Error()) - } else { - fmt.Println("s:", string(v)) - } - - type NewStruct struct { - NVS NullValStruct - S string - F float64 - } - ss := new(NewStruct) - - v, err = xml.Marshal(ss) - if err != nil { - fmt.Println("err:", err.Error()) - } else { - fmt.Println("ss:", string(v)) - } - - v, err = xml.MarshalIndent(ss," "," ") - if err != nil { - fmt.Println("err:", err.Error()) - } else { - fmt.Println("ss indent:\n",string(v)) - } - // Output: - // s: 0 - // s: 0 - // ss: 00 - // ss indent: - // - // - // 0 - // - // - // - // - // 0 - // -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/marshal.go.v1_2 b/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/marshal.go.v1_2 deleted file mode 100644 index b51d0c1e..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_marshal/marshal.go.v1_2 +++ /dev/null @@ -1,1034 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package xml - -import ( - "bufio" - "bytes" - "encoding" - "fmt" - "io" - "reflect" - "strconv" - "strings" -) - -const ( - // A generic XML header suitable for use with the output of Marshal. - // This is not automatically added to any output of this package, - // it is provided as a convenience. - Header = `` + "\n" -) - -// Marshal returns the XML encoding of v. -// -// Marshal handles an array or slice by marshalling each of the elements. -// Marshal handles a pointer by marshalling the value it points at or, if the -// pointer is nil, by writing nothing. Marshal handles an interface value by -// marshalling the value it contains or, if the interface value is nil, by -// writing nothing. Marshal handles all other data by writing one or more XML -// elements containing the data. -// -// The name for the XML elements is taken from, in order of preference: -// - the tag on the XMLName field, if the data is a struct -// - the value of the XMLName field of type xml.Name -// - the tag of the struct field used to obtain the data -// - the name of the struct field used to obtain the data -// - the name of the marshalled type -// -// The XML element for a struct contains marshalled elements for each of the -// exported fields of the struct, with these exceptions: -// - the XMLName field, described above, is omitted. -// - a field with tag "-" is omitted. -// - a field with tag "name,attr" becomes an attribute with -// the given name in the XML element. -// - a field with tag ",attr" becomes an attribute with the -// field name in the XML element. -// - a field with tag ",chardata" is written as character data, -// not as an XML element. -// - a field with tag ",innerxml" is written verbatim, not subject -// to the usual marshalling procedure. -// - a field with tag ",comment" is written as an XML comment, not -// subject to the usual marshalling procedure. It must not contain -// the "--" string within it. -// - a field with a tag including the "omitempty" option is omitted -// if the field value is empty. The empty values are false, 0, any -// nil pointer or interface value, and any array, slice, map, or -// string of length zero. -// - an anonymous struct field is handled as if the fields of its -// value were part of the outer struct. -// -// If a field uses a tag "a>b>c", then the element c will be nested inside -// parent elements a and b. Fields that appear next to each other that name -// the same parent will be enclosed in one XML element. -// -// See MarshalIndent for an example. -// -// Marshal will return an error if asked to marshal a channel, function, or map. -func Marshal(v interface{}) ([]byte, error) { - var b bytes.Buffer - if err := NewEncoder(&b).Encode(v); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -// Marshaler is the interface implemented by objects that can marshal -// themselves into valid XML elements. -// -// MarshalXML encodes the receiver as zero or more XML elements. -// By convention, arrays or slices are typically encoded as a sequence -// of elements, one per entry. -// Using start as the element tag is not required, but doing so -// will enable Unmarshal to match the XML elements to the correct -// struct field. -// One common implementation strategy is to construct a separate -// value with a layout corresponding to the desired XML and then -// to encode it using e.EncodeElement. -// Another common strategy is to use repeated calls to e.EncodeToken -// to generate the XML output one token at a time. -// The sequence of encoded tokens must make up zero or more valid -// XML elements. -type Marshaler interface { - MarshalXML(e *Encoder, start StartElement) error -} - -// MarshalerAttr is the interface implemented by objects that can marshal -// themselves into valid XML attributes. -// -// MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. -// Using name as the attribute name is not required, but doing so -// will enable Unmarshal to match the attribute to the correct -// struct field. -// If MarshalXMLAttr returns the zero attribute Attr{}, no attribute -// will be generated in the output. -// MarshalXMLAttr is used only for struct fields with the -// "attr" option in the field tag. -type MarshalerAttr interface { - MarshalXMLAttr(name Name) (Attr, error) -} - -// MarshalIndent works like Marshal, but each XML element begins on a new -// indented line that starts with prefix and is followed by one or more -// copies of indent according to the nesting depth. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - var b bytes.Buffer - enc := NewEncoder(&b) - enc.Indent(prefix, indent) - if err := enc.Encode(v); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -// An Encoder writes XML data to an output stream. -type Encoder struct { - p printer -} - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - e := &Encoder{printer{Writer: bufio.NewWriter(w)}} - e.p.encoder = e - return e -} - -// Indent sets the encoder to generate XML in which each element -// begins on a new indented line that starts with prefix and is followed by -// one or more copies of indent according to the nesting depth. -func (enc *Encoder) Indent(prefix, indent string) { - enc.p.prefix = prefix - enc.p.indent = indent -} - -// Encode writes the XML encoding of v to the stream. -// -// See the documentation for Marshal for details about the conversion -// of Go values to XML. -// -// Encode calls Flush before returning. -func (enc *Encoder) Encode(v interface{}) error { - err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) - if err != nil { - return err - } - return enc.p.Flush() -} - -// EncodeElement writes the XML encoding of v to the stream, -// using start as the outermost tag in the encoding. -// -// See the documentation for Marshal for details about the conversion -// of Go values to XML. -// -// EncodeElement calls Flush before returning. -func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { - err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) - if err != nil { - return err - } - return enc.p.Flush() -} - -var ( - endComment = []byte("-->") - endProcInst = []byte("?>") - endDirective = []byte(">") -) - -// EncodeToken writes the given XML token to the stream. -// It returns an error if StartElement and EndElement tokens are not properly matched. -// -// EncodeToken does not call Flush, because usually it is part of a larger operation -// such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked -// during those), and those will call Flush when finished. -// -// Callers that create an Encoder and then invoke EncodeToken directly, without -// using Encode or EncodeElement, need to call Flush when finished to ensure -// that the XML is written to the underlying writer. -func (enc *Encoder) EncodeToken(t Token) error { - p := &enc.p - switch t := t.(type) { - case StartElement: - if err := p.writeStart(&t); err != nil { - return err - } - case EndElement: - if err := p.writeEnd(t.Name); err != nil { - return err - } - case CharData: - EscapeText(p, t) - case Comment: - if bytes.Contains(t, endComment) { - return fmt.Errorf("xml: EncodeToken of Comment containing --> marker") - } - p.WriteString("") - return p.cachedWriteError() - case ProcInst: - if t.Target == "xml" || !isNameString(t.Target) { - return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target") - } - if bytes.Contains(t.Inst, endProcInst) { - return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker") - } - p.WriteString(" 0 { - p.WriteByte(' ') - p.Write(t.Inst) - } - p.WriteString("?>") - case Directive: - if bytes.Contains(t, endDirective) { - return fmt.Errorf("xml: EncodeToken of Directive containing > marker") - } - p.WriteString("") - } - return p.cachedWriteError() -} - -// Flush flushes any buffered XML to the underlying writer. -// See the EncodeToken documentation for details about when it is necessary. -func (enc *Encoder) Flush() error { - return enc.p.Flush() -} - -type printer struct { - *bufio.Writer - encoder *Encoder - seq int - indent string - prefix string - depth int - indentedIn bool - putNewline bool - attrNS map[string]string // map prefix -> name space - attrPrefix map[string]string // map name space -> prefix - prefixes []string - tags []Name -} - -// createAttrPrefix finds the name space prefix attribute to use for the given name space, -// defining a new prefix if necessary. It returns the prefix. -func (p *printer) createAttrPrefix(url string) string { - if prefix := p.attrPrefix[url]; prefix != "" { - return prefix - } - - // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml" - // and must be referred to that way. - // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns", - // but users should not be trying to use that one directly - that's our job.) - if url == xmlURL { - return "xml" - } - - // Need to define a new name space. - if p.attrPrefix == nil { - p.attrPrefix = make(map[string]string) - p.attrNS = make(map[string]string) - } - - // Pick a name. We try to use the final element of the path - // but fall back to _. - prefix := strings.TrimRight(url, "/") - if i := strings.LastIndex(prefix, "/"); i >= 0 { - prefix = prefix[i+1:] - } - if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { - prefix = "_" - } - if strings.HasPrefix(prefix, "xml") { - // xmlanything is reserved. - prefix = "_" + prefix - } - if p.attrNS[prefix] != "" { - // Name is taken. Find a better one. - for p.seq++; ; p.seq++ { - if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" { - prefix = id - break - } - } - } - - p.attrPrefix[url] = prefix - p.attrNS[prefix] = url - - p.WriteString(`xmlns:`) - p.WriteString(prefix) - p.WriteString(`="`) - EscapeText(p, []byte(url)) - p.WriteString(`" `) - - p.prefixes = append(p.prefixes, prefix) - - return prefix -} - -// deleteAttrPrefix removes an attribute name space prefix. -func (p *printer) deleteAttrPrefix(prefix string) { - delete(p.attrPrefix, p.attrNS[prefix]) - delete(p.attrNS, prefix) -} - -func (p *printer) markPrefix() { - p.prefixes = append(p.prefixes, "") -} - -func (p *printer) popPrefix() { - for len(p.prefixes) > 0 { - prefix := p.prefixes[len(p.prefixes)-1] - p.prefixes = p.prefixes[:len(p.prefixes)-1] - if prefix == "" { - break - } - p.deleteAttrPrefix(prefix) - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem() - textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() -) - -// CLB, 11/30/13 -var useNullEndTag bool - -// SetUseNullEndTag - 'true': have Marshal/MarshalIndent use in place of for empty element. -func SetUseNullEndTag(b bool) { - useNullEndTag = b -} - -// marshalValue writes one or more XML elements representing val. -// If val was obtained from a struct field, finfo must have its details. -func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error { - if startTemplate != nil && startTemplate.Name.Local == "" { - return fmt.Errorf("xml: EncodeElement of StartElement with missing name") - } - - if !val.IsValid() { - return nil - } - if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) { - return nil - } - - // Drill into interfaces and pointers. - // This can turn into an infinite loop given a cyclic chain, - // but it matches the Go 1 behavior. - for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { - if val.IsNil() { - return nil - } - val = val.Elem() - } - - kind := val.Kind() - typ := val.Type() - - // Check for marshaler. - if val.CanInterface() && typ.Implements(marshalerType) { - return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate)) - } - if val.CanAddr() { - pv := val.Addr() - if pv.CanInterface() && pv.Type().Implements(marshalerType) { - return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate)) - } - } - - // Check for text marshaler. - if val.CanInterface() && typ.Implements(textMarshalerType) { - return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate)) - } - if val.CanAddr() { - pv := val.Addr() - if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { - return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate)) - } - } - - // Slices and arrays iterate over the elements. They do not have an enclosing tag. - if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 { - for i, n := 0, val.Len(); i < n; i++ { - if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil { - return err - } - } - return nil - } - - tinfo, err := getTypeInfo(typ) - if err != nil { - return err - } - - // Create start element. - // Precedence for the XML element name is: - // 0. startTemplate - // 1. XMLName field in underlying struct; - // 2. field name/tag in the struct field; and - // 3. type name - var start StartElement - - if startTemplate != nil { - start.Name = startTemplate.Name - start.Attr = append(start.Attr, startTemplate.Attr...) - } else if tinfo.xmlname != nil { - xmlname := tinfo.xmlname - if xmlname.name != "" { - start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name - } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" { - start.Name = v - } - } - if start.Name.Local == "" && finfo != nil { - start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name - } - if start.Name.Local == "" { - name := typ.Name() - if name == "" { - return &UnsupportedTypeError{typ} - } - start.Name.Local = name - } - - // Attributes - for i := range tinfo.fields { - finfo := &tinfo.fields[i] - if finfo.flags&fAttr == 0 { - continue - } - fv := finfo.value(val) - name := Name{Space: finfo.xmlns, Local: finfo.name} - - if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) { - continue - } - - if fv.Kind() == reflect.Interface && fv.IsNil() { - continue - } - - if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) { - attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name) - if err != nil { - return err - } - if attr.Name.Local != "" { - start.Attr = append(start.Attr, attr) - } - continue - } - - if fv.CanAddr() { - pv := fv.Addr() - if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) { - attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name) - if err != nil { - return err - } - if attr.Name.Local != "" { - start.Attr = append(start.Attr, attr) - } - continue - } - } - - if fv.CanInterface() && fv.Type().Implements(textMarshalerType) { - text, err := fv.Interface().(encoding.TextMarshaler).MarshalText() - if err != nil { - return err - } - start.Attr = append(start.Attr, Attr{name, string(text)}) - continue - } - - if fv.CanAddr() { - pv := fv.Addr() - if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { - text, err := pv.Interface().(encoding.TextMarshaler).MarshalText() - if err != nil { - return err - } - start.Attr = append(start.Attr, Attr{name, string(text)}) - continue - } - } - - // Dereference or skip nil pointer, interface values. - switch fv.Kind() { - case reflect.Ptr, reflect.Interface: - if fv.IsNil() { - continue - } - fv = fv.Elem() - } - - s, b, err := p.marshalSimple(fv.Type(), fv) - if err != nil { - return err - } - if b != nil { - s = string(b) - } - start.Attr = append(start.Attr, Attr{name, s}) - } - -/* CLB, 11/30/13 - if err := p.writeStart(&start); err != nil { - return err - } -*/ - - // CLB, 11/30/13 - var noVal bool - - if val.Kind() == reflect.Struct { - if err := p.writeStart(&start); err != nil { - return err - } - err = p.marshalStruct(tinfo, val) - } else { - s, b, err1 := p.marshalSimple(typ, val) - // CLB, 11/30/13 - if s == "" && len(b) == 0 && useNullEndTag { - if err := p.writeStartDone(&start); err != nil { - return err - } - noVal = true - goto finishProc - } - if err := p.writeStart(&start); err != nil { - return err - } - if err1 != nil { - err = err1 - } else if b != nil { - EscapeText(p, b) - } else { - p.EscapeString(s) - } - } - if err != nil { - return err - } - -// CLB, 11/30/13 -finishProc: - - if noVal && useNullEndTag { - if err := p.writeEndDone(start.Name); err != nil { - return err - } - } else if err := p.writeEnd(start.Name); err != nil { - return err - } - - return p.cachedWriteError() -} - -// defaultStart returns the default start element to use, -// given the reflect type, field info, and start template. -func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { - var start StartElement - // Precedence for the XML element name is as above, - // except that we do not look inside structs for the first field. - if startTemplate != nil { - start.Name = startTemplate.Name - start.Attr = append(start.Attr, startTemplate.Attr...) - } else if finfo != nil && finfo.name != "" { - start.Name.Local = finfo.name - start.Name.Space = finfo.xmlns - } else if typ.Name() != "" { - start.Name.Local = typ.Name() - } else { - // Must be a pointer to a named type, - // since it has the Marshaler methods. - start.Name.Local = typ.Elem().Name() - } - return start -} - -// marshalInterface marshals a Marshaler interface value. -func (p *printer) marshalInterface(val Marshaler, start StartElement) error { - // Push a marker onto the tag stack so that MarshalXML - // cannot close the XML tags that it did not open. - p.tags = append(p.tags, Name{}) - n := len(p.tags) - - err := val.MarshalXML(p.encoder, start) - if err != nil { - return err - } - - // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. - if len(p.tags) > n { - return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) - } - p.tags = p.tags[:n-1] - return nil -} - -// marshalTextInterface marshals a TextMarshaler interface value. -func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { - if err := p.writeStart(&start); err != nil { - return err - } - text, err := val.MarshalText() - if err != nil { - return err - } - EscapeText(p, text) - return p.writeEnd(start.Name) -} - -// writeStart writes the given start element. -func (p *printer) writeStart(start *StartElement) error { - if start.Name.Local == "" { - return fmt.Errorf("xml: start tag with no name") - } - - p.tags = append(p.tags, start.Name) - p.markPrefix() - - p.writeIndent(1) - p.WriteByte('<') - p.WriteString(start.Name.Local) - - if start.Name.Space != "" { - p.WriteString(` xmlns="`) - p.EscapeString(start.Name.Space) - p.WriteByte('"') - } - - // Attributes - for _, attr := range start.Attr { - name := attr.Name - if name.Local == "" { - continue - } - p.WriteByte(' ') - if name.Space != "" { - p.WriteString(p.createAttrPrefix(name.Space)) - p.WriteByte(':') - } - p.WriteString(name.Local) - p.WriteString(`="`) - p.EscapeString(attr.Value) - p.WriteByte('"') - } - p.WriteByte('>') - return nil -} - -// CLB, 11/30/13 - -// writeStartDone writes the given start element. -func (p *printer) writeStartDone(start *StartElement) error { - if start.Name.Local == "" { - return fmt.Errorf("xml: start tag with no name") - } - - p.tags = append(p.tags, start.Name) - p.markPrefix() - - p.writeIndent(1) - p.WriteByte('<') - p.WriteString(start.Name.Local) - - if start.Name.Space != "" { - p.WriteString(` xmlns="`) - p.EscapeString(start.Name.Space) - p.WriteByte('"') - } - - // Attributes - for _, attr := range start.Attr { - name := attr.Name - if name.Local == "" { - continue - } - p.WriteByte(' ') - if name.Space != "" { - p.WriteString(p.createAttrPrefix(name.Space)) - p.WriteByte(':') - } - p.WriteString(name.Local) - p.WriteString(`="`) - p.EscapeString(attr.Value) - p.WriteByte('"') - } - // CLB, 11/30/13 - p.WriteString(`/>`) - return nil -} - -func (p *printer) writeEnd(name Name) error { - if name.Local == "" { - return fmt.Errorf("xml: end tag with no name") - } - if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" { - return fmt.Errorf("xml: end tag without start tag", name.Local) - } - if top := p.tags[len(p.tags)-1]; top != name { - if top.Local != name.Local { - return fmt.Errorf("xml: end tag does not match start tag <%s>", name.Local, top.Local) - } - return fmt.Errorf("xml: end tag in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space) - } - p.tags = p.tags[:len(p.tags)-1] - - p.writeIndent(-1) - p.WriteByte('<') - p.WriteByte('/') - p.WriteString(name.Local) - p.WriteByte('>') - p.popPrefix() - return nil -} - -// CLB, 11/30/13 -func (p *printer) writeEndDone(name Name) error { - if name.Local == "" { - return fmt.Errorf("xml: end tag with no name") - } - if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" { - return fmt.Errorf("xml: end tag without start tag", name.Local) - } - if top := p.tags[len(p.tags)-1]; top != name { - if top.Local != name.Local { - return fmt.Errorf("xml: end tag does not match start tag <%s>", name.Local, top.Local) - } - return fmt.Errorf("xml: end tag in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space) - } - p.tags = p.tags[:len(p.tags)-1] - -// CLB, 11/30/13 - p.writeIndent(-1) -/* - p.WriteByte('<') - p.WriteByte('/') - p.WriteString(name.Local) - p.WriteByte('>') -*/ - p.popPrefix() - return nil -} - -func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) { - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.FormatInt(val.Int(), 10), nil, nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return strconv.FormatUint(val.Uint(), 10), nil, nil - case reflect.Float32, reflect.Float64: - return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil - case reflect.String: - return val.String(), nil, nil - case reflect.Bool: - return strconv.FormatBool(val.Bool()), nil, nil - case reflect.Array: - if typ.Elem().Kind() != reflect.Uint8 { - break - } - // [...]byte - var bytes []byte - if val.CanAddr() { - bytes = val.Slice(0, val.Len()).Bytes() - } else { - bytes = make([]byte, val.Len()) - reflect.Copy(reflect.ValueOf(bytes), val) - } - return "", bytes, nil - case reflect.Slice: - if typ.Elem().Kind() != reflect.Uint8 { - break - } - // []byte - return "", val.Bytes(), nil - } - return "", nil, &UnsupportedTypeError{typ} -} - -var ddBytes = []byte("--") - -func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error { - s := parentStack{p: p} - for i := range tinfo.fields { - finfo := &tinfo.fields[i] - if finfo.flags&fAttr != 0 { - continue - } - vf := finfo.value(val) - - // Dereference or skip nil pointer, interface values. - switch vf.Kind() { - case reflect.Ptr, reflect.Interface: - if !vf.IsNil() { - vf = vf.Elem() - } - } - - switch finfo.flags & fMode { - case fCharData: - if vf.CanInterface() && vf.Type().Implements(textMarshalerType) { - data, err := vf.Interface().(encoding.TextMarshaler).MarshalText() - if err != nil { - return err - } - Escape(p, data) - continue - } - if vf.CanAddr() { - pv := vf.Addr() - if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { - data, err := pv.Interface().(encoding.TextMarshaler).MarshalText() - if err != nil { - return err - } - Escape(p, data) - continue - } - } - var scratch [64]byte - switch vf.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - Escape(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - Escape(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)) - case reflect.Float32, reflect.Float64: - Escape(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())) - case reflect.Bool: - Escape(p, strconv.AppendBool(scratch[:0], vf.Bool())) - case reflect.String: - if err := EscapeText(p, []byte(vf.String())); err != nil { - return err - } - case reflect.Slice: - if elem, ok := vf.Interface().([]byte); ok { - if err := EscapeText(p, elem); err != nil { - return err - } - } - } - continue - - case fComment: - k := vf.Kind() - if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) { - return fmt.Errorf("xml: bad type for comment field of %s", val.Type()) - } - if vf.Len() == 0 { - continue - } - p.writeIndent(0) - p.WriteString("" is invalid grammar. Make it "- -->" - p.WriteByte(' ') - } - p.WriteString("-->") - continue - - case fInnerXml: - iface := vf.Interface() - switch raw := iface.(type) { - case []byte: - p.Write(raw) - continue - case string: - p.WriteString(raw) - continue - } - - case fElement, fElement | fAny: - if err := s.trim(finfo.parents); err != nil { - return err - } - if len(finfo.parents) > len(s.stack) { - if vf.Kind() != reflect.Ptr && vf.Kind() != reflect.Interface || !vf.IsNil() { - if err := s.push(finfo.parents[len(s.stack):]); err != nil { - return err - } - } - } - } - if err := p.marshalValue(vf, finfo, nil); err != nil { - return err - } - } - s.trim(nil) - return p.cachedWriteError() -} - -// return the bufio Writer's cached write error -func (p *printer) cachedWriteError() error { - _, err := p.Write(nil) - return err -} - -func (p *printer) writeIndent(depthDelta int) { - if len(p.prefix) == 0 && len(p.indent) == 0 { - return - } - if depthDelta < 0 { - p.depth-- - if p.indentedIn { - p.indentedIn = false - return - } - p.indentedIn = false - } - if p.putNewline { - p.WriteByte('\n') - } else { - p.putNewline = true - } - if len(p.prefix) > 0 { - p.WriteString(p.prefix) - } - if len(p.indent) > 0 { - for i := 0; i < p.depth; i++ { - p.WriteString(p.indent) - } - } - if depthDelta > 0 { - p.depth++ - p.indentedIn = true - } -} - -type parentStack struct { - p *printer - stack []string -} - -// trim updates the XML context to match the longest common prefix of the stack -// and the given parents. A closing tag will be written for every parent -// popped. Passing a zero slice or nil will close all the elements. -func (s *parentStack) trim(parents []string) error { - split := 0 - for ; split < len(parents) && split < len(s.stack); split++ { - if parents[split] != s.stack[split] { - break - } - } - for i := len(s.stack) - 1; i >= split; i-- { - if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil { - return err - } - } - s.stack = parents[:split] - return nil -} - -// push adds parent elements to the stack and writes open tags. -func (s *parentStack) push(parents []string) error { - for i := 0; i < len(parents); i++ { - if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil { - return err - } - } - s.stack = append(s.stack, parents...) - return nil -} - -// A MarshalXMLError is returned when Marshal encounters a type -// that cannot be converted into XML. -type UnsupportedTypeError struct { - Type reflect.Type -} - -func (e *UnsupportedTypeError) Error() string { - return "xml: unsupported type: " + e.Type.String() -} - -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} diff --git a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_test.go b/Godeps/_workspace/src/github.com/clbanning/mxj/xml_test.go deleted file mode 100644 index 955923df..00000000 --- a/Godeps/_workspace/src/github.com/clbanning/mxj/xml_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package mxj - -import ( - "bytes" - "fmt" - "io" - "testing" -) - -func TestXmlHeader(t *testing.T) { - fmt.Println("\n---------------- xml_test.go ...\n") -} - -func TestNewMapXml(t *testing.T) { - x := []byte(`something more12`) - - mv, merr := NewMapXml(x) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - - fmt.Println("NewMapXml, x :", string(x)) - fmt.Println("NewMapXml, mv:", mv) -} - -func TestAttrHyphenFalse(t *testing.T) { - PrependAttrWithHyphen(false) - x := []byte(`something more12`) - - mv, merr := NewMapXml(x) - if merr != nil { - t.Fatal("merr:", merr.Error()) - } - - fmt.Println("AttrHyphenFalse, x :", string(x)) - fmt.Println("AttrHyphenFalse, mv:", mv) - PrependAttrWithHyphen(true) -} - -func TestNewMapXmlError(t *testing.T) { - x := []byte(`something more12`) - - m, merr := NewMapJson(x) - if merr == nil { - t.Fatal("NewMapXmlError, m:", m) - } - - fmt.Println("NewMapXmlError, x :", string(x)) - fmt.Println("NewMapXmlError, merr:", merr.Error()) - - x = []byte(`something more12`) - m, merr = NewMapJson(x) - if merr == nil { - t.Fatal("NewMapXmlError, m:", m) - } - - fmt.Println("NewMapXmlError, x :", string(x)) - fmt.Println("NewMapXmlError, merr:", merr.Error()) -} - -func TestNewMapXmlReader(t *testing.T) { - x := []byte(`is a testsomething more12`) - - r := bytes.NewReader(x) - - for { - m, raw, err := NewMapXmlReaderRaw(r) - if err != nil && err != io.EOF { - t.Fatal("err:", err.Error()) - } - if err == io.EOF && len(m) == 0 { - break - } - fmt.Println("NewMapXmlReader, raw:", string(raw)) - fmt.Println("NewMapXmlReader, m :", m) - } -} - -// --------------------- Xml() and XmlWriter() test cases ------------------- - -func TestXml_1(t *testing.T) { - mv := Map{"tag1": "some data", "tag2": "more data", "boolean": true, "float": 3.14159625, "null": nil} - - x, err := mv.Xml() - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("Xml_1, mv:", mv) - fmt.Println("Xml_1, x :", string(x)) -} - -func TestXml_2(t *testing.T) { - a := []interface{}{"string", true, 36.4} - mv := Map{"array": a} - - x, err := mv.Xml() - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("Xml_2, mv:", mv) - fmt.Println("Xml_2, x :", string(x)) -} - -func TestXml_3(t *testing.T) { - a := []interface{}{"string", true, 36.4} - mv := Map{"array": []interface{}{a, "string2"}} - - x, err := mv.Xml() - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("Xml_3, mv:", mv) - fmt.Println("Xml_3, x :", string(x)) -} - -func TestXml_4(t *testing.T) { - a := []interface{}{"string", true, 36.4} - mv := Map{"array": map[string]interface{}{"innerkey": []interface{}{a, "string2"}}} - - x, err := mv.Xml() - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("Xml_4, mv:", mv) - fmt.Println("Xml_4, x :", string(x)) -} - -func TestXml_5(t *testing.T) { - a := []interface{}{"string", true, 36.4} - mv := Map{"array": []interface{}{map[string]interface{}{"innerkey": []interface{}{a, "string2"}}, map[string]interface{}{"some": "more"}}} - - x, err := mv.Xml() - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("Xml_5, mv:", mv) - fmt.Println("Xml_5, x :", string(x)) -} - -func TestXmlWriter(t *testing.T) { - mv := Map{"tag1": "some data", "tag2": "more data", "boolean": true, "float": 3.14159625} - w := new(bytes.Buffer) - - raw, err := mv.XmlWriterRaw(w, "myRootTag") - if err != nil { - t.Fatal("err:", err.Error()) - } - - b := make([]byte, w.Len()) - _, err = w.Read(b) - if err != nil { - t.Fatal("err:", err.Error()) - } - - fmt.Println("XmlWriter, raw:", string(raw)) - fmt.Println("XmlWriter, b :", string(b)) -} - -// -------------------------- XML Handler test cases ------------------------- - -/* tested in bulk_test.go ... -var xhdata = []byte(`is a testsomething more12`) - -func TestHandleXmlReader(t *testing.T) { - fmt.Println("HandleXmlReader:", string(xhdata)) - - rdr := bytes.NewReader(xhdata) - err := HandleXmlReader(rdr, xmhandler, xehandler) - if err != nil { - t.Fatal("err:", err.Error()) - } -} - -var xt *testing.T - -func xmhandler(m Map, raw []byte) bool { - x, xerr := m.Xml() - if xerr != nil { - xt.Fatal("... xmhandler:", xerr.Error()) - return false - } - - fmt.Println("... xmhandler, raw:", string(raw)) - fmt.Println("... xmhandler, x :", string(x)) - return true -} - -func xehandler(err error, raw []byte) bool { - if err == nil { - // shouldn't be here - xt.Fatal("... xehandler: ") - return false - } - if err == io.EOF { - return true - } - - fmt.Println("... xehandler raw:", string(raw)) - fmt.Println("... xehandler err:", err.Error()) - return true -} -*/ diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/.gitignore b/Godeps/_workspace/src/github.com/stretchr/objx/.gitignore deleted file mode 100644 index 00268614..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/LICENSE.md b/Godeps/_workspace/src/github.com/stretchr/objx/LICENSE.md deleted file mode 100644 index 21999458..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/LICENSE.md +++ /dev/null @@ -1,23 +0,0 @@ -objx - by Mat Ryer and Tyler Bunnell - -The MIT License (MIT) - -Copyright (c) 2014 Stretchr, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/README.md b/Godeps/_workspace/src/github.com/stretchr/objx/README.md deleted file mode 100644 index 4aa18068..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# objx - - * Jump into the [API Documentation](http://godoc.org/github.com/stretchr/objx) diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/accessors.go b/Godeps/_workspace/src/github.com/stretchr/objx/accessors.go deleted file mode 100644 index 721bcac7..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/accessors.go +++ /dev/null @@ -1,179 +0,0 @@ -package objx - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// arrayAccesRegexString is the regex used to extract the array number -// from the access path -const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` - -// arrayAccesRegex is the compiled arrayAccesRegexString -var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) - -// Get gets the value using the specified selector and -// returns it inside a new Obj object. -// -// If it cannot find the value, Get will return a nil -// value inside an instance of Obj. -// -// Get can only operate directly on map[string]interface{} and []interface. -// -// Example -// -// To access the title of the third chapter of the second book, do: -// -// o.Get("books[1].chapters[2].title") -func (m Map) Get(selector string) *Value { - rawObj := access(m, selector, nil, false, false) - return &Value{data: rawObj} -} - -// Set sets the value using the specified selector and -// returns the object on which Set was called. -// -// Set can only operate directly on map[string]interface{} and []interface -// -// Example -// -// To set the title of the third chapter of the second book, do: -// -// o.Set("books[1].chapters[2].title","Time to Go") -func (m Map) Set(selector string, value interface{}) Map { - access(m, selector, value, true, false) - return m -} - -// access accesses the object using the selector and performs the -// appropriate action. -func access(current, selector, value interface{}, isSet, panics bool) interface{} { - - switch selector.(type) { - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - - if array, ok := current.([]interface{}); ok { - index := intFromInterface(selector) - - if index >= len(array) { - if panics { - panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) - } - return nil - } - - return array[index] - } - - return nil - - case string: - - selStr := selector.(string) - selSegs := strings.SplitN(selStr, PathSeparator, 2) - thisSel := selSegs[0] - index := -1 - var err error - - // https://github.com/stretchr/objx/issues/12 - if strings.Contains(thisSel, "[") { - - arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) - - if len(arrayMatches) > 0 { - - // Get the key into the map - thisSel = arrayMatches[1] - - // Get the index into the array at the key - index, err = strconv.Atoi(arrayMatches[2]) - - if err != nil { - // This should never happen. If it does, something has gone - // seriously wrong. Panic. - panic("objx: Array index is not an integer. Must use array[int].") - } - - } - } - - if curMap, ok := current.(Map); ok { - current = map[string]interface{}(curMap) - } - - // get the object in question - switch current.(type) { - case map[string]interface{}: - curMSI := current.(map[string]interface{}) - if len(selSegs) <= 1 && isSet { - curMSI[thisSel] = value - return nil - } else { - current = curMSI[thisSel] - } - default: - current = nil - } - - if current == nil && panics { - panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) - } - - // do we need to access the item of an array? - if index > -1 { - if array, ok := current.([]interface{}); ok { - if index < len(array) { - current = array[index] - } else { - if panics { - panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) - } - current = nil - } - } - } - - if len(selSegs) > 1 { - current = access(current, selSegs[1], value, isSet, panics) - } - - } - - return current - -} - -// intFromInterface converts an interface object to the largest -// representation of an unsigned integer using a type switch and -// assertions -func intFromInterface(selector interface{}) int { - var value int - switch selector.(type) { - case int: - value = selector.(int) - case int8: - value = int(selector.(int8)) - case int16: - value = int(selector.(int16)) - case int32: - value = int(selector.(int32)) - case int64: - value = int(selector.(int64)) - case uint: - value = int(selector.(uint)) - case uint8: - value = int(selector.(uint8)) - case uint16: - value = int(selector.(uint16)) - case uint32: - value = int(selector.(uint32)) - case uint64: - value = int(selector.(uint64)) - default: - panic("objx: array access argument is not an integer type (this should never happen)") - } - - return value -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go deleted file mode 100644 index ce5d8e4a..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestAccessorsAccessGetSingleField(t *testing.T) { - - current := map[string]interface{}{"name": "Tyler"} - assert.Equal(t, "Tyler", access(current, "name", nil, false, true)) - -} -func TestAccessorsAccessGetDeep(t *testing.T) { - - current := map[string]interface{}{"name": map[string]interface{}{"first": "Tyler", "last": "Bunnell"}} - assert.Equal(t, "Tyler", access(current, "name.first", nil, false, true)) - assert.Equal(t, "Bunnell", access(current, "name.last", nil, false, true)) - -} -func TestAccessorsAccessGetDeepDeep(t *testing.T) { - - current := map[string]interface{}{"one": map[string]interface{}{"two": map[string]interface{}{"three": map[string]interface{}{"four": 4}}}} - assert.Equal(t, 4, access(current, "one.two.three.four", nil, false, true)) - -} -func TestAccessorsAccessGetInsideArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}}} - assert.Equal(t, "Tyler", access(current, "names[0].first", nil, false, true)) - assert.Equal(t, "Bunnell", access(current, "names[0].last", nil, false, true)) - assert.Equal(t, "Capitol", access(current, "names[1].first", nil, false, true)) - assert.Equal(t, "Bollocks", access(current, "names[1].last", nil, false, true)) - - assert.Panics(t, func() { - access(current, "names[2]", nil, false, true) - }) - assert.Nil(t, access(current, "names[2]", nil, false, false)) - -} - -func TestAccessorsAccessGetFromArrayWithInt(t *testing.T) { - - current := []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}} - one := access(current, 0, nil, false, false) - two := access(current, 1, nil, false, false) - three := access(current, 2, nil, false, false) - - assert.Equal(t, "Tyler", one.(map[string]interface{})["first"]) - assert.Equal(t, "Capitol", two.(map[string]interface{})["first"]) - assert.Nil(t, three) - -} - -func TestAccessorsGet(t *testing.T) { - - current := New(map[string]interface{}{"name": "Tyler"}) - assert.Equal(t, "Tyler", current.Get("name").data) - -} - -func TestAccessorsAccessSetSingleField(t *testing.T) { - - current := map[string]interface{}{"name": "Tyler"} - access(current, "name", "Mat", true, false) - assert.Equal(t, current["name"], "Mat") - - access(current, "age", 29, true, true) - assert.Equal(t, current["age"], 29) - -} - -func TestAccessorsAccessSetSingleFieldNotExisting(t *testing.T) { - - current := map[string]interface{}{} - access(current, "name", "Mat", true, false) - assert.Equal(t, current["name"], "Mat") - -} - -func TestAccessorsAccessSetDeep(t *testing.T) { - - current := map[string]interface{}{"name": map[string]interface{}{"first": "Tyler", "last": "Bunnell"}} - - access(current, "name.first", "Mat", true, true) - access(current, "name.last", "Ryer", true, true) - - assert.Equal(t, "Mat", access(current, "name.first", nil, false, true)) - assert.Equal(t, "Ryer", access(current, "name.last", nil, false, true)) - -} -func TestAccessorsAccessSetDeepDeep(t *testing.T) { - - current := map[string]interface{}{"one": map[string]interface{}{"two": map[string]interface{}{"three": map[string]interface{}{"four": 4}}}} - - access(current, "one.two.three.four", 5, true, true) - - assert.Equal(t, 5, access(current, "one.two.three.four", nil, false, true)) - -} -func TestAccessorsAccessSetArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{"Tyler"}} - - access(current, "names[0]", "Mat", true, true) - - assert.Equal(t, "Mat", access(current, "names[0]", nil, false, true)) - -} -func TestAccessorsAccessSetInsideArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}}} - - access(current, "names[0].first", "Mat", true, true) - access(current, "names[0].last", "Ryer", true, true) - access(current, "names[1].first", "Captain", true, true) - access(current, "names[1].last", "Underpants", true, true) - - assert.Equal(t, "Mat", access(current, "names[0].first", nil, false, true)) - assert.Equal(t, "Ryer", access(current, "names[0].last", nil, false, true)) - assert.Equal(t, "Captain", access(current, "names[1].first", nil, false, true)) - assert.Equal(t, "Underpants", access(current, "names[1].last", nil, false, true)) - -} - -func TestAccessorsAccessSetFromArrayWithInt(t *testing.T) { - - current := []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}} - one := access(current, 0, nil, false, false) - two := access(current, 1, nil, false, false) - three := access(current, 2, nil, false, false) - - assert.Equal(t, "Tyler", one.(map[string]interface{})["first"]) - assert.Equal(t, "Capitol", two.(map[string]interface{})["first"]) - assert.Nil(t, three) - -} - -func TestAccessorsSet(t *testing.T) { - - current := New(map[string]interface{}{"name": "Tyler"}) - current.Set("name", "Mat") - assert.Equal(t, "Mat", current.Get("name").data) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/array-access.txt b/Godeps/_workspace/src/github.com/stretchr/objx/codegen/array-access.txt deleted file mode 100644 index 30602347..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/array-access.txt +++ /dev/null @@ -1,14 +0,0 @@ - case []{1}: - a := object.([]{1}) - if isSet { - a[index] = value.({1}) - } else { - if index >= len(a) { - if panics { - panic(fmt.Sprintf("objx: Index %d is out of range because the []{1} only contains %d items.", index, len(a))) - } - return nil - } else { - return a[index] - } - } diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/index.html b/Godeps/_workspace/src/github.com/stretchr/objx/codegen/index.html deleted file mode 100644 index 379ffc3c..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/index.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - Codegen - - - - - -

- Template -

-

- Use {x} as a placeholder for each argument. -

- - -

- Arguments (comma separated) -

-

- One block per line -

- - -

- Output -

- - - - - - - - diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/template.txt b/Godeps/_workspace/src/github.com/stretchr/objx/codegen/template.txt deleted file mode 100644 index b396900b..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/template.txt +++ /dev/null @@ -1,286 +0,0 @@ -/* - {4} ({1} and []{1}) - -------------------------------------------------- -*/ - -// {4} gets the value as a {1}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) {4}(optionalDefault ...{1}) {1} { - if s, ok := v.data.({1}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return {3} -} - -// Must{4} gets the value as a {1}. -// -// Panics if the object is not a {1}. -func (v *Value) Must{4}() {1} { - return v.data.({1}) -} - -// {4}Slice gets the value as a []{1}, returns the optionalDefault -// value or nil if the value is not a []{1}. -func (v *Value) {4}Slice(optionalDefault ...[]{1}) []{1} { - if s, ok := v.data.([]{1}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// Must{4}Slice gets the value as a []{1}. -// -// Panics if the object is not a []{1}. -func (v *Value) Must{4}Slice() []{1} { - return v.data.([]{1}) -} - -// Is{4} gets whether the object contained is a {1} or not. -func (v *Value) Is{4}() bool { - _, ok := v.data.({1}) - return ok -} - -// Is{4}Slice gets whether the object contained is a []{1} or not. -func (v *Value) Is{4}Slice() bool { - _, ok := v.data.([]{1}) - return ok -} - -// Each{4} calls the specified callback for each object -// in the []{1}. -// -// Panics if the object is the wrong type. -func (v *Value) Each{4}(callback func(int, {1}) bool) *Value { - - for index, val := range v.Must{4}Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// Where{4} uses the specified decider function to select items -// from the []{1}. The object contained in the result will contain -// only the selected items. -func (v *Value) Where{4}(decider func(int, {1}) bool) *Value { - - var selected []{1} - - v.Each{4}(func(index int, val {1}) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data:selected} - -} - -// Group{4} uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]{1}. -func (v *Value) Group{4}(grouper func(int, {1}) string) *Value { - - groups := make(map[string][]{1}) - - v.Each{4}(func(index int, val {1}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]{1}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data:groups} - -} - -// Replace{4} uses the specified function to replace each {1}s -// by iterating each item. The data in the returned result will be a -// []{1} containing the replaced items. -func (v *Value) Replace{4}(replacer func(int, {1}) {1}) *Value { - - arr := v.Must{4}Slice() - replaced := make([]{1}, len(arr)) - - v.Each{4}(func(index int, val {1}) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data:replaced} - -} - -// Collect{4} uses the specified collector function to collect a value -// for each of the {1}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) Collect{4}(collector func(int, {1}) interface{}) *Value { - - arr := v.Must{4}Slice() - collected := make([]interface{}, len(arr)) - - v.Each{4}(func(index int, val {1}) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data:collected} -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func Test{4}(t *testing.T) { - - val := {1}( {2} ) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").{4}()) - assert.Equal(t, val, New(m).Get("value").Must{4}()) - assert.Equal(t, {1}({3}), New(m).Get("nothing").{4}()) - assert.Equal(t, val, New(m).Get("nothing").{4}({2})) - - assert.Panics(t, func() { - New(m).Get("age").Must{4}() - }) - -} - -func Test{4}Slice(t *testing.T) { - - val := {1}( {2} ) - m := map[string]interface{}{"value": []{1}{ val }, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").{4}Slice()[0]) - assert.Equal(t, val, New(m).Get("value").Must{4}Slice()[0]) - assert.Equal(t, []{1}(nil), New(m).Get("nothing").{4}Slice()) - assert.Equal(t, val, New(m).Get("nothing").{4}Slice( []{1}{ {1}({2}) } )[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").Must{4}Slice() - }) - -} - -func TestIs{4}(t *testing.T) { - - var v *Value - - v = &Value{data: {1}({2})} - assert.True(t, v.Is{4}()) - - v = &Value{data: []{1}{ {1}({2}) }} - assert.True(t, v.Is{4}Slice()) - -} - -func TestEach{4}(t *testing.T) { - - v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} - count := 0 - replacedVals := make([]{1}, 0) - assert.Equal(t, v, v.Each{4}(func(i int, val {1}) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.Must{4}Slice()[0]) - assert.Equal(t, replacedVals[1], v.Must{4}Slice()[1]) - assert.Equal(t, replacedVals[2], v.Must{4}Slice()[2]) - -} - -func TestWhere{4}(t *testing.T) { - - v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} - - selected := v.Where{4}(func(i int, val {1}) bool { - return i%2==0 - }).Must{4}Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroup{4}(t *testing.T) { - - v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} - - grouped := v.Group{4}(func(i int, val {1}) string { - return fmt.Sprintf("%v", i%2==0) - }).data.(map[string][]{1}) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplace{4}(t *testing.T) { - - v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} - - rawArr := v.Must{4}Slice() - - replaced := v.Replace{4}(func(index int, val {1}) {1} { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.Must{4}Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollect{4}(t *testing.T) { - - v := &Value{data: []{1}{ {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}), {1}({2}) }} - - collected := v.Collect{4}(func(index int, val {1}) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/types_list.txt b/Godeps/_workspace/src/github.com/stretchr/objx/codegen/types_list.txt deleted file mode 100644 index 069d43d8..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/codegen/types_list.txt +++ /dev/null @@ -1,20 +0,0 @@ -Interface,interface{},"something",nil,Inter -Map,map[string]interface{},map[string]interface{}{"name":"Tyler"},nil,MSI -ObjxMap,(Map),New(1),New(nil),ObjxMap -Bool,bool,true,false,Bool -String,string,"hello","",Str -Int,int,1,0,Int -Int8,int8,1,0,Int8 -Int16,int16,1,0,Int16 -Int32,int32,1,0,Int32 -Int64,int64,1,0,Int64 -Uint,uint,1,0,Uint -Uint8,uint8,1,0,Uint8 -Uint16,uint16,1,0,Uint16 -Uint32,uint32,1,0,Uint32 -Uint64,uint64,1,0,Uint64 -Uintptr,uintptr,1,0,Uintptr -Float32,float32,1,0,Float32 -Float64,float64,1,0,Float64 -Complex64,complex64,1,0,Complex64 -Complex128,complex128,1,0,Complex128 diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/constants.go b/Godeps/_workspace/src/github.com/stretchr/objx/constants.go deleted file mode 100644 index f9eb42a2..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/constants.go +++ /dev/null @@ -1,13 +0,0 @@ -package objx - -const ( - // PathSeparator is the character used to separate the elements - // of the keypath. - // - // For example, `location.address.city` - PathSeparator string = "." - - // SignatureSeparator is the character that is used to - // separate the Base64 string from the security signature. - SignatureSeparator = "_" -) diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/conversions.go b/Godeps/_workspace/src/github.com/stretchr/objx/conversions.go deleted file mode 100644 index 9cdfa9f9..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/conversions.go +++ /dev/null @@ -1,117 +0,0 @@ -package objx - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/url" -) - -// JSON converts the contained object to a JSON string -// representation -func (m Map) JSON() (string, error) { - - result, err := json.Marshal(m) - - if err != nil { - err = errors.New("objx: JSON encode failed with: " + err.Error()) - } - - return string(result), err - -} - -// MustJSON converts the contained object to a JSON string -// representation and panics if there is an error -func (m Map) MustJSON() string { - result, err := m.JSON() - if err != nil { - panic(err.Error()) - } - return result -} - -// Base64 converts the contained object to a Base64 string -// representation of the JSON string representation -func (m Map) Base64() (string, error) { - - var buf bytes.Buffer - - jsonData, err := m.JSON() - if err != nil { - return "", err - } - - encoder := base64.NewEncoder(base64.StdEncoding, &buf) - encoder.Write([]byte(jsonData)) - encoder.Close() - - return buf.String(), nil - -} - -// MustBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and panics -// if there is an error -func (m Map) MustBase64() string { - result, err := m.Base64() - if err != nil { - panic(err.Error()) - } - return result -} - -// SignedBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and signs it -// using the provided key. -func (m Map) SignedBase64(key string) (string, error) { - - base64, err := m.Base64() - if err != nil { - return "", err - } - - sig := HashWithKey(base64, key) - - return base64 + SignatureSeparator + sig, nil - -} - -// MustSignedBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and signs it -// using the provided key and panics if there is an error -func (m Map) MustSignedBase64(key string) string { - result, err := m.SignedBase64(key) - if err != nil { - panic(err.Error()) - } - return result -} - -/* - URL Query - ------------------------------------------------ -*/ - -// URLValues creates a url.Values object from an Obj. This -// function requires that the wrapped object be a map[string]interface{} -func (m Map) URLValues() url.Values { - - vals := make(url.Values) - - for k, v := range m { - //TODO: can this be done without sprintf? - vals.Set(k, fmt.Sprintf("%v", v)) - } - - return vals -} - -// URLQuery gets an encoded URL query representing the given -// Obj. This function requires that the wrapped object be a -// map[string]interface{} -func (m Map) URLQuery() (string, error) { - return m.URLValues().Encode(), nil -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go deleted file mode 100644 index e9ccd298..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestConversionJSON(t *testing.T) { - - jsonString := `{"name":"Mat"}` - o := MustFromJSON(jsonString) - - result, err := o.JSON() - - if assert.NoError(t, err) { - assert.Equal(t, jsonString, result) - } - - assert.Equal(t, jsonString, o.MustJSON()) - -} - -func TestConversionJSONWithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustJSON() - }) - - _, err := o.JSON() - - assert.Error(t, err) - -} - -func TestConversionBase64(t *testing.T) { - - o := New(map[string]interface{}{"name": "Mat"}) - - result, err := o.Base64() - - if assert.NoError(t, err) { - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", result) - } - - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", o.MustBase64()) - -} - -func TestConversionBase64WithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustBase64() - }) - - _, err := o.Base64() - - assert.Error(t, err) - -} - -func TestConversionSignedBase64(t *testing.T) { - - o := New(map[string]interface{}{"name": "Mat"}) - - result, err := o.SignedBase64("key") - - if assert.NoError(t, err) { - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", result) - } - - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", o.MustSignedBase64("key")) - -} - -func TestConversionSignedBase64WithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustSignedBase64("key") - }) - - _, err := o.SignedBase64("key") - - assert.Error(t, err) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/doc.go b/Godeps/_workspace/src/github.com/stretchr/objx/doc.go deleted file mode 100644 index 47bf85e4..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/doc.go +++ /dev/null @@ -1,72 +0,0 @@ -// objx - Go package for dealing with maps, slices, JSON and other data. -// -// Overview -// -// Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes -// a powerful `Get` method (among others) that allows you to easily and quickly get -// access to data within the map, without having to worry too much about type assertions, -// missing data, default values etc. -// -// Pattern -// -// Objx uses a preditable pattern to make access data from within `map[string]interface{}'s -// easy. -// -// Call one of the `objx.` functions to create your `objx.Map` to get going: -// -// m, err := objx.FromJSON(json) -// -// NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, -// the rest will be optimistic and try to figure things out without panicking. -// -// Use `Get` to access the value you're interested in. You can use dot and array -// notation too: -// -// m.Get("places[0].latlng") -// -// Once you have saught the `Value` you're interested in, you can use the `Is*` methods -// to determine its type. -// -// if m.Get("code").IsStr() { /* ... */ } -// -// Or you can just assume the type, and use one of the strong type methods to -// extract the real value: -// -// m.Get("code").Int() -// -// If there's no value there (or if it's the wrong type) then a default value -// will be returned, or you can be explicit about the default value. -// -// Get("code").Int(-1) -// -// If you're dealing with a slice of data as a value, Objx provides many useful -// methods for iterating, manipulating and selecting that data. You can find out more -// by exploring the index below. -// -// Reading data -// -// A simple example of how to use Objx: -// -// // use MustFromJSON to make an objx.Map from some JSON -// m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) -// -// // get the details -// name := m.Get("name").Str() -// age := m.Get("age").Int() -// -// // get their nickname (or use their name if they -// // don't have one) -// nickname := m.Get("nickname").Str(name) -// -// Ranging -// -// Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For -// example, to `range` the data, do what you would expect: -// -// m := objx.MustFromJSON(json) -// for key, value := range m { -// -// /* ... do your magic ... */ -// -// } -package objx diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go deleted file mode 100644 index 27f7d904..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -var fixtures = []struct { - // name is the name of the fixture (used for reporting - // failures) - name string - // data is the JSON data to be worked on - data string - // get is the argument(s) to pass to Get - get interface{} - // output is the expected output - output interface{} -}{ - { - name: "Simple get", - data: `{"name": "Mat"}`, - get: "name", - output: "Mat", - }, - { - name: "Get with dot notation", - data: `{"address": {"city": "Boulder"}}`, - get: "address.city", - output: "Boulder", - }, - { - name: "Deep get with dot notation", - data: `{"one": {"two": {"three": {"four": "hello"}}}}`, - get: "one.two.three.four", - output: "hello", - }, - { - name: "Get missing with dot notation", - data: `{"one": {"two": {"three": {"four": "hello"}}}}`, - get: "one.ten", - output: nil, - }, - { - name: "Get with array notation", - data: `{"tags": ["one", "two", "three"]}`, - get: "tags[1]", - output: "two", - }, - { - name: "Get with array and dot notation", - data: `{"types": { "tags": ["one", "two", "three"]}}`, - get: "types.tags[1]", - output: "two", - }, - { - name: "Get with array and dot notation - field after array", - data: `{"tags": [{"name":"one"}, {"name":"two"}, {"name":"three"}]}`, - get: "tags[1].name", - output: "two", - }, - { - name: "Complex get with array and dot notation", - data: `{"tags": [{"list": [{"one":"pizza"}]}]}`, - get: "tags[0].list[0].one", - output: "pizza", - }, - { - name: "Get field from within string should be nil", - data: `{"name":"Tyler"}`, - get: "name.something", - output: nil, - }, - { - name: "Get field from within string (using array accessor) should be nil", - data: `{"numbers":["one", "two", "three"]}`, - get: "numbers[0].nope", - output: nil, - }, -} - -func TestFixtures(t *testing.T) { - - for _, fixture := range fixtures { - - m := MustFromJSON(fixture.data) - - // get the value - t.Logf("Running get fixture: \"%s\" (%v)", fixture.name, fixture) - value := m.Get(fixture.get.(string)) - - // make sure it matches - assert.Equal(t, fixture.output, value.data, - "Get fixture \"%s\" failed: %v", fixture.name, fixture, - ) - - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/map.go b/Godeps/_workspace/src/github.com/stretchr/objx/map.go deleted file mode 100644 index eb6ed8e2..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/map.go +++ /dev/null @@ -1,222 +0,0 @@ -package objx - -import ( - "encoding/base64" - "encoding/json" - "errors" - "io/ioutil" - "net/url" - "strings" -) - -// MSIConvertable is an interface that defines methods for converting your -// custom types to a map[string]interface{} representation. -type MSIConvertable interface { - // MSI gets a map[string]interface{} (msi) representing the - // object. - MSI() map[string]interface{} -} - -// Map provides extended functionality for working with -// untyped data, in particular map[string]interface (msi). -type Map map[string]interface{} - -// Value returns the internal value instance -func (m Map) Value() *Value { - return &Value{data: m} -} - -// Nil represents a nil Map. -var Nil Map = New(nil) - -// New creates a new Map containing the map[string]interface{} in the data argument. -// If the data argument is not a map[string]interface, New attempts to call the -// MSI() method on the MSIConvertable interface to create one. -func New(data interface{}) Map { - if _, ok := data.(map[string]interface{}); !ok { - if converter, ok := data.(MSIConvertable); ok { - data = converter.MSI() - } else { - return nil - } - } - return Map(data.(map[string]interface{})) -} - -// MSI creates a map[string]interface{} and puts it inside a new Map. -// -// The arguments follow a key, value pattern. -// -// Panics -// -// Panics if any key arugment is non-string or if there are an odd number of arguments. -// -// Example -// -// To easily create Maps: -// -// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) -// -// // creates an Map equivalent to -// m := objx.New(map[string]interface{}{"name": "Mat", "age": 29, "subobj": map[string]interface{}{"active": true}}) -func MSI(keyAndValuePairs ...interface{}) Map { - - newMap := make(map[string]interface{}) - keyAndValuePairsLen := len(keyAndValuePairs) - - if keyAndValuePairsLen%2 != 0 { - panic("objx: MSI must have an even number of arguments following the 'key, value' pattern.") - } - - for i := 0; i < keyAndValuePairsLen; i = i + 2 { - - key := keyAndValuePairs[i] - value := keyAndValuePairs[i+1] - - // make sure the key is a string - keyString, keyStringOK := key.(string) - if !keyStringOK { - panic("objx: MSI must follow 'string, interface{}' pattern. " + keyString + " is not a valid key.") - } - - newMap[keyString] = value - - } - - return New(newMap) -} - -// ****** Conversion Constructors - -// MustFromJSON creates a new Map containing the data specified in the -// jsonString. -// -// Panics if the JSON is invalid. -func MustFromJSON(jsonString string) Map { - o, err := FromJSON(jsonString) - - if err != nil { - panic("objx: MustFromJSON failed with error: " + err.Error()) - } - - return o -} - -// FromJSON creates a new Map containing the data specified in the -// jsonString. -// -// Returns an error if the JSON is invalid. -func FromJSON(jsonString string) (Map, error) { - - var data interface{} - err := json.Unmarshal([]byte(jsonString), &data) - - if err != nil { - return Nil, err - } - - return New(data), nil - -} - -// FromBase64 creates a new Obj containing the data specified -// in the Base64 string. -// -// The string is an encoded JSON string returned by Base64 -func FromBase64(base64String string) (Map, error) { - - decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) - - decoded, err := ioutil.ReadAll(decoder) - if err != nil { - return nil, err - } - - return FromJSON(string(decoded)) -} - -// MustFromBase64 creates a new Obj containing the data specified -// in the Base64 string and panics if there is an error. -// -// The string is an encoded JSON string returned by Base64 -func MustFromBase64(base64String string) Map { - - result, err := FromBase64(base64String) - - if err != nil { - panic("objx: MustFromBase64 failed with error: " + err.Error()) - } - - return result -} - -// FromSignedBase64 creates a new Obj containing the data specified -// in the Base64 string. -// -// The string is an encoded JSON string returned by SignedBase64 -func FromSignedBase64(base64String, key string) (Map, error) { - parts := strings.Split(base64String, SignatureSeparator) - if len(parts) != 2 { - return nil, errors.New("objx: Signed base64 string is malformed.") - } - - sig := HashWithKey(parts[0], key) - if parts[1] != sig { - return nil, errors.New("objx: Signature for base64 data does not match.") - } - - return FromBase64(parts[0]) -} - -// MustFromSignedBase64 creates a new Obj containing the data specified -// in the Base64 string and panics if there is an error. -// -// The string is an encoded JSON string returned by Base64 -func MustFromSignedBase64(base64String, key string) Map { - - result, err := FromSignedBase64(base64String, key) - - if err != nil { - panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) - } - - return result -} - -// FromURLQuery generates a new Obj by parsing the specified -// query. -// -// For queries with multiple values, the first value is selected. -func FromURLQuery(query string) (Map, error) { - - vals, err := url.ParseQuery(query) - - if err != nil { - return nil, err - } - - m := make(map[string]interface{}) - for k, vals := range vals { - m[k] = vals[0] - } - - return New(m), nil -} - -// MustFromURLQuery generates a new Obj by parsing the specified -// query. -// -// For queries with multiple values, the first value is selected. -// -// Panics if it encounters an error -func MustFromURLQuery(query string) Map { - - o, err := FromURLQuery(query) - - if err != nil { - panic("objx: MustFromURLQuery failed with error: " + err.Error()) - } - - return o - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go deleted file mode 100644 index 6beb5067..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go +++ /dev/null @@ -1,10 +0,0 @@ -package objx - -var TestMap map[string]interface{} = map[string]interface{}{ - "name": "Tyler", - "address": map[string]interface{}{ - "city": "Salt Lake City", - "state": "UT", - }, - "numbers": []interface{}{"one", "two", "three", "four", "five"}, -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go deleted file mode 100644 index 1f8b45c6..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -type Convertable struct { - name string -} - -func (c *Convertable) MSI() map[string]interface{} { - return map[string]interface{}{"name": c.name} -} - -type Unconvertable struct { - name string -} - -func TestMapCreation(t *testing.T) { - - o := New(nil) - assert.Nil(t, o) - - o = New("Tyler") - assert.Nil(t, o) - - unconvertable := &Unconvertable{name: "Tyler"} - o = New(unconvertable) - assert.Nil(t, o) - - convertable := &Convertable{name: "Tyler"} - o = New(convertable) - if assert.NotNil(t, convertable) { - assert.Equal(t, "Tyler", o["name"], "Tyler") - } - - o = MSI() - if assert.NotNil(t, o) { - assert.NotNil(t, o) - } - - o = MSI("name", "Tyler") - if assert.NotNil(t, o) { - if assert.NotNil(t, o) { - assert.Equal(t, o["name"], "Tyler") - } - } - -} - -func TestMapMustFromJSONWithError(t *testing.T) { - - _, err := FromJSON(`"name":"Mat"}`) - assert.Error(t, err) - -} - -func TestMapFromJSON(t *testing.T) { - - o := MustFromJSON(`{"name":"Mat"}`) - - if assert.NotNil(t, o) { - if assert.NotNil(t, o) { - assert.Equal(t, "Mat", o["name"]) - } - } - -} - -func TestMapFromJSONWithError(t *testing.T) { - - var m Map - - assert.Panics(t, func() { - m = MustFromJSON(`"name":"Mat"}`) - }) - - assert.Nil(t, m) - -} - -func TestMapFromBase64String(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWF0In0=" - - o, err := FromBase64(base64String) - - if assert.NoError(t, err) { - assert.Equal(t, o.Get("name").Str(), "Mat") - } - - assert.Equal(t, MustFromBase64(base64String).Get("name").Str(), "Mat") - -} - -func TestMapFromBase64StringWithError(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWFasd0In0=" - - _, err := FromBase64(base64String) - - assert.Error(t, err) - - assert.Panics(t, func() { - MustFromBase64(base64String) - }) - -} - -func TestMapFromSignedBase64String(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" - - o, err := FromSignedBase64(base64String, "key") - - if assert.NoError(t, err) { - assert.Equal(t, o.Get("name").Str(), "Mat") - } - - assert.Equal(t, MustFromSignedBase64(base64String, "key").Get("name").Str(), "Mat") - -} - -func TestMapFromSignedBase64StringWithError(t *testing.T) { - - base64String := "eyJuYW1lasdIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" - - _, err := FromSignedBase64(base64String, "key") - - assert.Error(t, err) - - assert.Panics(t, func() { - MustFromSignedBase64(base64String, "key") - }) - -} - -func TestMapFromURLQuery(t *testing.T) { - - m, err := FromURLQuery("name=tyler&state=UT") - if assert.NoError(t, err) && assert.NotNil(t, m) { - assert.Equal(t, "tyler", m.Get("name").Str()) - assert.Equal(t, "UT", m.Get("state").Str()) - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/mutations.go b/Godeps/_workspace/src/github.com/stretchr/objx/mutations.go deleted file mode 100644 index b35c8639..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/mutations.go +++ /dev/null @@ -1,81 +0,0 @@ -package objx - -// Exclude returns a new Map with the keys in the specified []string -// excluded. -func (d Map) Exclude(exclude []string) Map { - - excluded := make(Map) - for k, v := range d { - var shouldInclude bool = true - for _, toExclude := range exclude { - if k == toExclude { - shouldInclude = false - break - } - } - if shouldInclude { - excluded[k] = v - } - } - - return excluded -} - -// Copy creates a shallow copy of the Obj. -func (m Map) Copy() Map { - copied := make(map[string]interface{}) - for k, v := range m { - copied[k] = v - } - return New(copied) -} - -// Merge blends the specified map with a copy of this map and returns the result. -// -// Keys that appear in both will be selected from the specified map. -// This method requires that the wrapped object be a map[string]interface{} -func (m Map) Merge(merge Map) Map { - return m.Copy().MergeHere(merge) -} - -// Merge blends the specified map with this map and returns the current map. -// -// Keys that appear in both will be selected from the specified map. The original map -// will be modified. This method requires that -// the wrapped object be a map[string]interface{} -func (m Map) MergeHere(merge Map) Map { - - for k, v := range merge { - m[k] = v - } - - return m - -} - -// Transform builds a new Obj giving the transformer a chance -// to change the keys and values as it goes. This method requires that -// the wrapped object be a map[string]interface{} -func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { - newMap := make(map[string]interface{}) - for k, v := range m { - modifiedKey, modifiedVal := transformer(k, v) - newMap[modifiedKey] = modifiedVal - } - return New(newMap) -} - -// TransformKeys builds a new map using the specified key mapping. -// -// Unspecified keys will be unaltered. -// This method requires that the wrapped object be a map[string]interface{} -func (m Map) TransformKeys(mapping map[string]string) Map { - return m.Transform(func(key string, value interface{}) (string, interface{}) { - - if newKey, ok := mapping[key]; ok { - return newKey, value - } - - return key, value - }) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go deleted file mode 100644 index e20ee23b..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestExclude(t *testing.T) { - - d := make(Map) - d["name"] = "Mat" - d["age"] = 29 - d["secret"] = "ABC" - - excluded := d.Exclude([]string{"secret"}) - - assert.Equal(t, d["name"], excluded["name"]) - assert.Equal(t, d["age"], excluded["age"]) - assert.False(t, excluded.Has("secret"), "secret should be excluded") - -} - -func TestCopy(t *testing.T) { - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - d1Obj := New(d1) - d2Obj := d1Obj.Copy() - - d2Obj["name"] = "Mat" - - assert.Equal(t, d1Obj.Get("name").Str(), "Tyler") - assert.Equal(t, d2Obj.Get("name").Str(), "Mat") - -} - -func TestMerge(t *testing.T) { - - d := make(map[string]interface{}) - d["name"] = "Mat" - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - dObj := New(d) - d1Obj := New(d1) - - merged := dObj.Merge(d1Obj) - - assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) - assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) - assert.Empty(t, dObj.Get("location").Str()) - -} - -func TestMergeHere(t *testing.T) { - - d := make(map[string]interface{}) - d["name"] = "Mat" - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - dObj := New(d) - d1Obj := New(d1) - - merged := dObj.MergeHere(d1Obj) - - assert.Equal(t, dObj, merged, "With MergeHere, it should return the first modified map") - assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) - assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) - assert.Equal(t, merged.Get("location").Str(), dObj.Get("location").Str()) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/security.go b/Godeps/_workspace/src/github.com/stretchr/objx/security.go deleted file mode 100644 index fdd6be9c..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/security.go +++ /dev/null @@ -1,14 +0,0 @@ -package objx - -import ( - "crypto/sha1" - "encoding/hex" -) - -// HashWithKey hashes the specified string using the security -// key. -func HashWithKey(data, key string) string { - hash := sha1.New() - hash.Write([]byte(data + ":" + key)) - return hex.EncodeToString(hash.Sum(nil)) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go deleted file mode 100644 index 8f0898f6..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestHashWithKey(t *testing.T) { - - assert.Equal(t, "0ce84d8d01f2c7b6e0882b784429c54d280ea2d9", HashWithKey("abc", "def")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go deleted file mode 100644 index 5408c7fd..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestSimpleExample(t *testing.T) { - - // build a map from a JSON object - o := MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`) - - // Map can be used as a straight map[string]interface{} - assert.Equal(t, o["name"], "Mat") - - // Get an Value object - v := o.Get("name") - assert.Equal(t, v, &Value{data: "Mat"}) - - // Test the contained value - assert.False(t, v.IsInt()) - assert.False(t, v.IsBool()) - assert.True(t, v.IsStr()) - - // Get the contained value - assert.Equal(t, v.Str(), "Mat") - - // Get a default value if the contained value is not of the expected type or does not exist - assert.Equal(t, 1, v.Int(1)) - - // Get a value by using array notation - assert.Equal(t, "indian", o.Get("foods[0]").Data()) - - // Set a value by using array notation - o.Set("foods[0]", "italian") - assert.Equal(t, "italian", o.Get("foods[0]").Str()) - - // Get a value by using dot notation - assert.Equal(t, "hobbiton", o.Get("location.county").Str()) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/tests.go b/Godeps/_workspace/src/github.com/stretchr/objx/tests.go deleted file mode 100644 index d9e0b479..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/tests.go +++ /dev/null @@ -1,17 +0,0 @@ -package objx - -// Has gets whether there is something at the specified selector -// or not. -// -// If m is nil, Has will always return false. -func (m Map) Has(selector string) bool { - if m == nil { - return false - } - return !m.Get(selector).IsNil() -} - -// IsNil gets whether the data is nil or not. -func (v *Value) IsNil() bool { - return v == nil || v.data == nil -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go deleted file mode 100644 index bcc1eb03..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestHas(t *testing.T) { - - m := New(TestMap) - - assert.True(t, m.Has("name")) - assert.True(t, m.Has("address.state")) - assert.True(t, m.Has("numbers[4]")) - - assert.False(t, m.Has("address.state.nope")) - assert.False(t, m.Has("address.nope")) - assert.False(t, m.Has("nope")) - assert.False(t, m.Has("numbers[5]")) - - m = nil - assert.False(t, m.Has("nothing")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen.go b/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen.go deleted file mode 100644 index f3ecb29b..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen.go +++ /dev/null @@ -1,2881 +0,0 @@ -package objx - -/* - Inter (interface{} and []interface{}) - -------------------------------------------------- -*/ - -// Inter gets the value as a interface{}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Inter(optionalDefault ...interface{}) interface{} { - if s, ok := v.data.(interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInter gets the value as a interface{}. -// -// Panics if the object is not a interface{}. -func (v *Value) MustInter() interface{} { - return v.data.(interface{}) -} - -// InterSlice gets the value as a []interface{}, returns the optionalDefault -// value or nil if the value is not a []interface{}. -func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { - if s, ok := v.data.([]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInterSlice gets the value as a []interface{}. -// -// Panics if the object is not a []interface{}. -func (v *Value) MustInterSlice() []interface{} { - return v.data.([]interface{}) -} - -// IsInter gets whether the object contained is a interface{} or not. -func (v *Value) IsInter() bool { - _, ok := v.data.(interface{}) - return ok -} - -// IsInterSlice gets whether the object contained is a []interface{} or not. -func (v *Value) IsInterSlice() bool { - _, ok := v.data.([]interface{}) - return ok -} - -// EachInter calls the specified callback for each object -// in the []interface{}. -// -// Panics if the object is the wrong type. -func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { - - for index, val := range v.MustInterSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInter uses the specified decider function to select items -// from the []interface{}. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { - - var selected []interface{} - - v.EachInter(func(index int, val interface{}) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInter uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]interface{}. -func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { - - groups := make(map[string][]interface{}) - - v.EachInter(func(index int, val interface{}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]interface{}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInter uses the specified function to replace each interface{}s -// by iterating each item. The data in the returned result will be a -// []interface{} containing the replaced items. -func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { - - arr := v.MustInterSlice() - replaced := make([]interface{}, len(arr)) - - v.EachInter(func(index int, val interface{}) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInter uses the specified collector function to collect a value -// for each of the interface{}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { - - arr := v.MustInterSlice() - collected := make([]interface{}, len(arr)) - - v.EachInter(func(index int, val interface{}) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - MSI (map[string]interface{} and []map[string]interface{}) - -------------------------------------------------- -*/ - -// MSI gets the value as a map[string]interface{}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { - if s, ok := v.data.(map[string]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustMSI gets the value as a map[string]interface{}. -// -// Panics if the object is not a map[string]interface{}. -func (v *Value) MustMSI() map[string]interface{} { - return v.data.(map[string]interface{}) -} - -// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault -// value or nil if the value is not a []map[string]interface{}. -func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { - if s, ok := v.data.([]map[string]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustMSISlice gets the value as a []map[string]interface{}. -// -// Panics if the object is not a []map[string]interface{}. -func (v *Value) MustMSISlice() []map[string]interface{} { - return v.data.([]map[string]interface{}) -} - -// IsMSI gets whether the object contained is a map[string]interface{} or not. -func (v *Value) IsMSI() bool { - _, ok := v.data.(map[string]interface{}) - return ok -} - -// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. -func (v *Value) IsMSISlice() bool { - _, ok := v.data.([]map[string]interface{}) - return ok -} - -// EachMSI calls the specified callback for each object -// in the []map[string]interface{}. -// -// Panics if the object is the wrong type. -func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { - - for index, val := range v.MustMSISlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereMSI uses the specified decider function to select items -// from the []map[string]interface{}. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { - - var selected []map[string]interface{} - - v.EachMSI(func(index int, val map[string]interface{}) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupMSI uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]map[string]interface{}. -func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { - - groups := make(map[string][]map[string]interface{}) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]map[string]interface{}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceMSI uses the specified function to replace each map[string]interface{}s -// by iterating each item. The data in the returned result will be a -// []map[string]interface{} containing the replaced items. -func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { - - arr := v.MustMSISlice() - replaced := make([]map[string]interface{}, len(arr)) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectMSI uses the specified collector function to collect a value -// for each of the map[string]interface{}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { - - arr := v.MustMSISlice() - collected := make([]interface{}, len(arr)) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - ObjxMap ((Map) and [](Map)) - -------------------------------------------------- -*/ - -// ObjxMap gets the value as a (Map), returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { - if s, ok := v.data.((Map)); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return New(nil) -} - -// MustObjxMap gets the value as a (Map). -// -// Panics if the object is not a (Map). -func (v *Value) MustObjxMap() Map { - return v.data.((Map)) -} - -// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault -// value or nil if the value is not a [](Map). -func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { - if s, ok := v.data.([](Map)); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustObjxMapSlice gets the value as a [](Map). -// -// Panics if the object is not a [](Map). -func (v *Value) MustObjxMapSlice() [](Map) { - return v.data.([](Map)) -} - -// IsObjxMap gets whether the object contained is a (Map) or not. -func (v *Value) IsObjxMap() bool { - _, ok := v.data.((Map)) - return ok -} - -// IsObjxMapSlice gets whether the object contained is a [](Map) or not. -func (v *Value) IsObjxMapSlice() bool { - _, ok := v.data.([](Map)) - return ok -} - -// EachObjxMap calls the specified callback for each object -// in the [](Map). -// -// Panics if the object is the wrong type. -func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { - - for index, val := range v.MustObjxMapSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereObjxMap uses the specified decider function to select items -// from the [](Map). The object contained in the result will contain -// only the selected items. -func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { - - var selected [](Map) - - v.EachObjxMap(func(index int, val Map) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupObjxMap uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][](Map). -func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { - - groups := make(map[string][](Map)) - - v.EachObjxMap(func(index int, val Map) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([](Map), 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceObjxMap uses the specified function to replace each (Map)s -// by iterating each item. The data in the returned result will be a -// [](Map) containing the replaced items. -func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { - - arr := v.MustObjxMapSlice() - replaced := make([](Map), len(arr)) - - v.EachObjxMap(func(index int, val Map) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectObjxMap uses the specified collector function to collect a value -// for each of the (Map)s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { - - arr := v.MustObjxMapSlice() - collected := make([]interface{}, len(arr)) - - v.EachObjxMap(func(index int, val Map) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Bool (bool and []bool) - -------------------------------------------------- -*/ - -// Bool gets the value as a bool, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Bool(optionalDefault ...bool) bool { - if s, ok := v.data.(bool); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return false -} - -// MustBool gets the value as a bool. -// -// Panics if the object is not a bool. -func (v *Value) MustBool() bool { - return v.data.(bool) -} - -// BoolSlice gets the value as a []bool, returns the optionalDefault -// value or nil if the value is not a []bool. -func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { - if s, ok := v.data.([]bool); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustBoolSlice gets the value as a []bool. -// -// Panics if the object is not a []bool. -func (v *Value) MustBoolSlice() []bool { - return v.data.([]bool) -} - -// IsBool gets whether the object contained is a bool or not. -func (v *Value) IsBool() bool { - _, ok := v.data.(bool) - return ok -} - -// IsBoolSlice gets whether the object contained is a []bool or not. -func (v *Value) IsBoolSlice() bool { - _, ok := v.data.([]bool) - return ok -} - -// EachBool calls the specified callback for each object -// in the []bool. -// -// Panics if the object is the wrong type. -func (v *Value) EachBool(callback func(int, bool) bool) *Value { - - for index, val := range v.MustBoolSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereBool uses the specified decider function to select items -// from the []bool. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereBool(decider func(int, bool) bool) *Value { - - var selected []bool - - v.EachBool(func(index int, val bool) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupBool uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]bool. -func (v *Value) GroupBool(grouper func(int, bool) string) *Value { - - groups := make(map[string][]bool) - - v.EachBool(func(index int, val bool) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]bool, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceBool uses the specified function to replace each bools -// by iterating each item. The data in the returned result will be a -// []bool containing the replaced items. -func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { - - arr := v.MustBoolSlice() - replaced := make([]bool, len(arr)) - - v.EachBool(func(index int, val bool) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectBool uses the specified collector function to collect a value -// for each of the bools in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { - - arr := v.MustBoolSlice() - collected := make([]interface{}, len(arr)) - - v.EachBool(func(index int, val bool) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Str (string and []string) - -------------------------------------------------- -*/ - -// Str gets the value as a string, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Str(optionalDefault ...string) string { - if s, ok := v.data.(string); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return "" -} - -// MustStr gets the value as a string. -// -// Panics if the object is not a string. -func (v *Value) MustStr() string { - return v.data.(string) -} - -// StrSlice gets the value as a []string, returns the optionalDefault -// value or nil if the value is not a []string. -func (v *Value) StrSlice(optionalDefault ...[]string) []string { - if s, ok := v.data.([]string); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustStrSlice gets the value as a []string. -// -// Panics if the object is not a []string. -func (v *Value) MustStrSlice() []string { - return v.data.([]string) -} - -// IsStr gets whether the object contained is a string or not. -func (v *Value) IsStr() bool { - _, ok := v.data.(string) - return ok -} - -// IsStrSlice gets whether the object contained is a []string or not. -func (v *Value) IsStrSlice() bool { - _, ok := v.data.([]string) - return ok -} - -// EachStr calls the specified callback for each object -// in the []string. -// -// Panics if the object is the wrong type. -func (v *Value) EachStr(callback func(int, string) bool) *Value { - - for index, val := range v.MustStrSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereStr uses the specified decider function to select items -// from the []string. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereStr(decider func(int, string) bool) *Value { - - var selected []string - - v.EachStr(func(index int, val string) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupStr uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]string. -func (v *Value) GroupStr(grouper func(int, string) string) *Value { - - groups := make(map[string][]string) - - v.EachStr(func(index int, val string) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]string, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceStr uses the specified function to replace each strings -// by iterating each item. The data in the returned result will be a -// []string containing the replaced items. -func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { - - arr := v.MustStrSlice() - replaced := make([]string, len(arr)) - - v.EachStr(func(index int, val string) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectStr uses the specified collector function to collect a value -// for each of the strings in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { - - arr := v.MustStrSlice() - collected := make([]interface{}, len(arr)) - - v.EachStr(func(index int, val string) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int (int and []int) - -------------------------------------------------- -*/ - -// Int gets the value as a int, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int(optionalDefault ...int) int { - if s, ok := v.data.(int); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt gets the value as a int. -// -// Panics if the object is not a int. -func (v *Value) MustInt() int { - return v.data.(int) -} - -// IntSlice gets the value as a []int, returns the optionalDefault -// value or nil if the value is not a []int. -func (v *Value) IntSlice(optionalDefault ...[]int) []int { - if s, ok := v.data.([]int); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustIntSlice gets the value as a []int. -// -// Panics if the object is not a []int. -func (v *Value) MustIntSlice() []int { - return v.data.([]int) -} - -// IsInt gets whether the object contained is a int or not. -func (v *Value) IsInt() bool { - _, ok := v.data.(int) - return ok -} - -// IsIntSlice gets whether the object contained is a []int or not. -func (v *Value) IsIntSlice() bool { - _, ok := v.data.([]int) - return ok -} - -// EachInt calls the specified callback for each object -// in the []int. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt(callback func(int, int) bool) *Value { - - for index, val := range v.MustIntSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt uses the specified decider function to select items -// from the []int. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt(decider func(int, int) bool) *Value { - - var selected []int - - v.EachInt(func(index int, val int) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int. -func (v *Value) GroupInt(grouper func(int, int) string) *Value { - - groups := make(map[string][]int) - - v.EachInt(func(index int, val int) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt uses the specified function to replace each ints -// by iterating each item. The data in the returned result will be a -// []int containing the replaced items. -func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { - - arr := v.MustIntSlice() - replaced := make([]int, len(arr)) - - v.EachInt(func(index int, val int) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt uses the specified collector function to collect a value -// for each of the ints in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { - - arr := v.MustIntSlice() - collected := make([]interface{}, len(arr)) - - v.EachInt(func(index int, val int) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int8 (int8 and []int8) - -------------------------------------------------- -*/ - -// Int8 gets the value as a int8, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int8(optionalDefault ...int8) int8 { - if s, ok := v.data.(int8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt8 gets the value as a int8. -// -// Panics if the object is not a int8. -func (v *Value) MustInt8() int8 { - return v.data.(int8) -} - -// Int8Slice gets the value as a []int8, returns the optionalDefault -// value or nil if the value is not a []int8. -func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { - if s, ok := v.data.([]int8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt8Slice gets the value as a []int8. -// -// Panics if the object is not a []int8. -func (v *Value) MustInt8Slice() []int8 { - return v.data.([]int8) -} - -// IsInt8 gets whether the object contained is a int8 or not. -func (v *Value) IsInt8() bool { - _, ok := v.data.(int8) - return ok -} - -// IsInt8Slice gets whether the object contained is a []int8 or not. -func (v *Value) IsInt8Slice() bool { - _, ok := v.data.([]int8) - return ok -} - -// EachInt8 calls the specified callback for each object -// in the []int8. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt8(callback func(int, int8) bool) *Value { - - for index, val := range v.MustInt8Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt8 uses the specified decider function to select items -// from the []int8. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { - - var selected []int8 - - v.EachInt8(func(index int, val int8) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt8 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int8. -func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { - - groups := make(map[string][]int8) - - v.EachInt8(func(index int, val int8) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int8, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt8 uses the specified function to replace each int8s -// by iterating each item. The data in the returned result will be a -// []int8 containing the replaced items. -func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { - - arr := v.MustInt8Slice() - replaced := make([]int8, len(arr)) - - v.EachInt8(func(index int, val int8) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt8 uses the specified collector function to collect a value -// for each of the int8s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { - - arr := v.MustInt8Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt8(func(index int, val int8) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int16 (int16 and []int16) - -------------------------------------------------- -*/ - -// Int16 gets the value as a int16, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int16(optionalDefault ...int16) int16 { - if s, ok := v.data.(int16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt16 gets the value as a int16. -// -// Panics if the object is not a int16. -func (v *Value) MustInt16() int16 { - return v.data.(int16) -} - -// Int16Slice gets the value as a []int16, returns the optionalDefault -// value or nil if the value is not a []int16. -func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { - if s, ok := v.data.([]int16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt16Slice gets the value as a []int16. -// -// Panics if the object is not a []int16. -func (v *Value) MustInt16Slice() []int16 { - return v.data.([]int16) -} - -// IsInt16 gets whether the object contained is a int16 or not. -func (v *Value) IsInt16() bool { - _, ok := v.data.(int16) - return ok -} - -// IsInt16Slice gets whether the object contained is a []int16 or not. -func (v *Value) IsInt16Slice() bool { - _, ok := v.data.([]int16) - return ok -} - -// EachInt16 calls the specified callback for each object -// in the []int16. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt16(callback func(int, int16) bool) *Value { - - for index, val := range v.MustInt16Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt16 uses the specified decider function to select items -// from the []int16. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { - - var selected []int16 - - v.EachInt16(func(index int, val int16) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt16 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int16. -func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { - - groups := make(map[string][]int16) - - v.EachInt16(func(index int, val int16) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int16, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt16 uses the specified function to replace each int16s -// by iterating each item. The data in the returned result will be a -// []int16 containing the replaced items. -func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { - - arr := v.MustInt16Slice() - replaced := make([]int16, len(arr)) - - v.EachInt16(func(index int, val int16) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt16 uses the specified collector function to collect a value -// for each of the int16s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { - - arr := v.MustInt16Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt16(func(index int, val int16) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int32 (int32 and []int32) - -------------------------------------------------- -*/ - -// Int32 gets the value as a int32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int32(optionalDefault ...int32) int32 { - if s, ok := v.data.(int32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt32 gets the value as a int32. -// -// Panics if the object is not a int32. -func (v *Value) MustInt32() int32 { - return v.data.(int32) -} - -// Int32Slice gets the value as a []int32, returns the optionalDefault -// value or nil if the value is not a []int32. -func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { - if s, ok := v.data.([]int32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt32Slice gets the value as a []int32. -// -// Panics if the object is not a []int32. -func (v *Value) MustInt32Slice() []int32 { - return v.data.([]int32) -} - -// IsInt32 gets whether the object contained is a int32 or not. -func (v *Value) IsInt32() bool { - _, ok := v.data.(int32) - return ok -} - -// IsInt32Slice gets whether the object contained is a []int32 or not. -func (v *Value) IsInt32Slice() bool { - _, ok := v.data.([]int32) - return ok -} - -// EachInt32 calls the specified callback for each object -// in the []int32. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt32(callback func(int, int32) bool) *Value { - - for index, val := range v.MustInt32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt32 uses the specified decider function to select items -// from the []int32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { - - var selected []int32 - - v.EachInt32(func(index int, val int32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int32. -func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { - - groups := make(map[string][]int32) - - v.EachInt32(func(index int, val int32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt32 uses the specified function to replace each int32s -// by iterating each item. The data in the returned result will be a -// []int32 containing the replaced items. -func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { - - arr := v.MustInt32Slice() - replaced := make([]int32, len(arr)) - - v.EachInt32(func(index int, val int32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt32 uses the specified collector function to collect a value -// for each of the int32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { - - arr := v.MustInt32Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt32(func(index int, val int32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int64 (int64 and []int64) - -------------------------------------------------- -*/ - -// Int64 gets the value as a int64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int64(optionalDefault ...int64) int64 { - if s, ok := v.data.(int64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt64 gets the value as a int64. -// -// Panics if the object is not a int64. -func (v *Value) MustInt64() int64 { - return v.data.(int64) -} - -// Int64Slice gets the value as a []int64, returns the optionalDefault -// value or nil if the value is not a []int64. -func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { - if s, ok := v.data.([]int64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt64Slice gets the value as a []int64. -// -// Panics if the object is not a []int64. -func (v *Value) MustInt64Slice() []int64 { - return v.data.([]int64) -} - -// IsInt64 gets whether the object contained is a int64 or not. -func (v *Value) IsInt64() bool { - _, ok := v.data.(int64) - return ok -} - -// IsInt64Slice gets whether the object contained is a []int64 or not. -func (v *Value) IsInt64Slice() bool { - _, ok := v.data.([]int64) - return ok -} - -// EachInt64 calls the specified callback for each object -// in the []int64. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt64(callback func(int, int64) bool) *Value { - - for index, val := range v.MustInt64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt64 uses the specified decider function to select items -// from the []int64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { - - var selected []int64 - - v.EachInt64(func(index int, val int64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int64. -func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { - - groups := make(map[string][]int64) - - v.EachInt64(func(index int, val int64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt64 uses the specified function to replace each int64s -// by iterating each item. The data in the returned result will be a -// []int64 containing the replaced items. -func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { - - arr := v.MustInt64Slice() - replaced := make([]int64, len(arr)) - - v.EachInt64(func(index int, val int64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt64 uses the specified collector function to collect a value -// for each of the int64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { - - arr := v.MustInt64Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt64(func(index int, val int64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint (uint and []uint) - -------------------------------------------------- -*/ - -// Uint gets the value as a uint, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint(optionalDefault ...uint) uint { - if s, ok := v.data.(uint); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint gets the value as a uint. -// -// Panics if the object is not a uint. -func (v *Value) MustUint() uint { - return v.data.(uint) -} - -// UintSlice gets the value as a []uint, returns the optionalDefault -// value or nil if the value is not a []uint. -func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { - if s, ok := v.data.([]uint); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUintSlice gets the value as a []uint. -// -// Panics if the object is not a []uint. -func (v *Value) MustUintSlice() []uint { - return v.data.([]uint) -} - -// IsUint gets whether the object contained is a uint or not. -func (v *Value) IsUint() bool { - _, ok := v.data.(uint) - return ok -} - -// IsUintSlice gets whether the object contained is a []uint or not. -func (v *Value) IsUintSlice() bool { - _, ok := v.data.([]uint) - return ok -} - -// EachUint calls the specified callback for each object -// in the []uint. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint(callback func(int, uint) bool) *Value { - - for index, val := range v.MustUintSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint uses the specified decider function to select items -// from the []uint. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint(decider func(int, uint) bool) *Value { - - var selected []uint - - v.EachUint(func(index int, val uint) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint. -func (v *Value) GroupUint(grouper func(int, uint) string) *Value { - - groups := make(map[string][]uint) - - v.EachUint(func(index int, val uint) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint uses the specified function to replace each uints -// by iterating each item. The data in the returned result will be a -// []uint containing the replaced items. -func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { - - arr := v.MustUintSlice() - replaced := make([]uint, len(arr)) - - v.EachUint(func(index int, val uint) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint uses the specified collector function to collect a value -// for each of the uints in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { - - arr := v.MustUintSlice() - collected := make([]interface{}, len(arr)) - - v.EachUint(func(index int, val uint) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint8 (uint8 and []uint8) - -------------------------------------------------- -*/ - -// Uint8 gets the value as a uint8, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint8(optionalDefault ...uint8) uint8 { - if s, ok := v.data.(uint8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint8 gets the value as a uint8. -// -// Panics if the object is not a uint8. -func (v *Value) MustUint8() uint8 { - return v.data.(uint8) -} - -// Uint8Slice gets the value as a []uint8, returns the optionalDefault -// value or nil if the value is not a []uint8. -func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { - if s, ok := v.data.([]uint8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint8Slice gets the value as a []uint8. -// -// Panics if the object is not a []uint8. -func (v *Value) MustUint8Slice() []uint8 { - return v.data.([]uint8) -} - -// IsUint8 gets whether the object contained is a uint8 or not. -func (v *Value) IsUint8() bool { - _, ok := v.data.(uint8) - return ok -} - -// IsUint8Slice gets whether the object contained is a []uint8 or not. -func (v *Value) IsUint8Slice() bool { - _, ok := v.data.([]uint8) - return ok -} - -// EachUint8 calls the specified callback for each object -// in the []uint8. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { - - for index, val := range v.MustUint8Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint8 uses the specified decider function to select items -// from the []uint8. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { - - var selected []uint8 - - v.EachUint8(func(index int, val uint8) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint8 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint8. -func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { - - groups := make(map[string][]uint8) - - v.EachUint8(func(index int, val uint8) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint8, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint8 uses the specified function to replace each uint8s -// by iterating each item. The data in the returned result will be a -// []uint8 containing the replaced items. -func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { - - arr := v.MustUint8Slice() - replaced := make([]uint8, len(arr)) - - v.EachUint8(func(index int, val uint8) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint8 uses the specified collector function to collect a value -// for each of the uint8s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { - - arr := v.MustUint8Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint8(func(index int, val uint8) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint16 (uint16 and []uint16) - -------------------------------------------------- -*/ - -// Uint16 gets the value as a uint16, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint16(optionalDefault ...uint16) uint16 { - if s, ok := v.data.(uint16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint16 gets the value as a uint16. -// -// Panics if the object is not a uint16. -func (v *Value) MustUint16() uint16 { - return v.data.(uint16) -} - -// Uint16Slice gets the value as a []uint16, returns the optionalDefault -// value or nil if the value is not a []uint16. -func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { - if s, ok := v.data.([]uint16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint16Slice gets the value as a []uint16. -// -// Panics if the object is not a []uint16. -func (v *Value) MustUint16Slice() []uint16 { - return v.data.([]uint16) -} - -// IsUint16 gets whether the object contained is a uint16 or not. -func (v *Value) IsUint16() bool { - _, ok := v.data.(uint16) - return ok -} - -// IsUint16Slice gets whether the object contained is a []uint16 or not. -func (v *Value) IsUint16Slice() bool { - _, ok := v.data.([]uint16) - return ok -} - -// EachUint16 calls the specified callback for each object -// in the []uint16. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { - - for index, val := range v.MustUint16Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint16 uses the specified decider function to select items -// from the []uint16. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { - - var selected []uint16 - - v.EachUint16(func(index int, val uint16) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint16 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint16. -func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { - - groups := make(map[string][]uint16) - - v.EachUint16(func(index int, val uint16) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint16, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint16 uses the specified function to replace each uint16s -// by iterating each item. The data in the returned result will be a -// []uint16 containing the replaced items. -func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { - - arr := v.MustUint16Slice() - replaced := make([]uint16, len(arr)) - - v.EachUint16(func(index int, val uint16) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint16 uses the specified collector function to collect a value -// for each of the uint16s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { - - arr := v.MustUint16Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint16(func(index int, val uint16) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint32 (uint32 and []uint32) - -------------------------------------------------- -*/ - -// Uint32 gets the value as a uint32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint32(optionalDefault ...uint32) uint32 { - if s, ok := v.data.(uint32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint32 gets the value as a uint32. -// -// Panics if the object is not a uint32. -func (v *Value) MustUint32() uint32 { - return v.data.(uint32) -} - -// Uint32Slice gets the value as a []uint32, returns the optionalDefault -// value or nil if the value is not a []uint32. -func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { - if s, ok := v.data.([]uint32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint32Slice gets the value as a []uint32. -// -// Panics if the object is not a []uint32. -func (v *Value) MustUint32Slice() []uint32 { - return v.data.([]uint32) -} - -// IsUint32 gets whether the object contained is a uint32 or not. -func (v *Value) IsUint32() bool { - _, ok := v.data.(uint32) - return ok -} - -// IsUint32Slice gets whether the object contained is a []uint32 or not. -func (v *Value) IsUint32Slice() bool { - _, ok := v.data.([]uint32) - return ok -} - -// EachUint32 calls the specified callback for each object -// in the []uint32. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { - - for index, val := range v.MustUint32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint32 uses the specified decider function to select items -// from the []uint32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { - - var selected []uint32 - - v.EachUint32(func(index int, val uint32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint32. -func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { - - groups := make(map[string][]uint32) - - v.EachUint32(func(index int, val uint32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint32 uses the specified function to replace each uint32s -// by iterating each item. The data in the returned result will be a -// []uint32 containing the replaced items. -func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { - - arr := v.MustUint32Slice() - replaced := make([]uint32, len(arr)) - - v.EachUint32(func(index int, val uint32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint32 uses the specified collector function to collect a value -// for each of the uint32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { - - arr := v.MustUint32Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint32(func(index int, val uint32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint64 (uint64 and []uint64) - -------------------------------------------------- -*/ - -// Uint64 gets the value as a uint64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint64(optionalDefault ...uint64) uint64 { - if s, ok := v.data.(uint64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint64 gets the value as a uint64. -// -// Panics if the object is not a uint64. -func (v *Value) MustUint64() uint64 { - return v.data.(uint64) -} - -// Uint64Slice gets the value as a []uint64, returns the optionalDefault -// value or nil if the value is not a []uint64. -func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { - if s, ok := v.data.([]uint64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint64Slice gets the value as a []uint64. -// -// Panics if the object is not a []uint64. -func (v *Value) MustUint64Slice() []uint64 { - return v.data.([]uint64) -} - -// IsUint64 gets whether the object contained is a uint64 or not. -func (v *Value) IsUint64() bool { - _, ok := v.data.(uint64) - return ok -} - -// IsUint64Slice gets whether the object contained is a []uint64 or not. -func (v *Value) IsUint64Slice() bool { - _, ok := v.data.([]uint64) - return ok -} - -// EachUint64 calls the specified callback for each object -// in the []uint64. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { - - for index, val := range v.MustUint64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint64 uses the specified decider function to select items -// from the []uint64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { - - var selected []uint64 - - v.EachUint64(func(index int, val uint64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint64. -func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { - - groups := make(map[string][]uint64) - - v.EachUint64(func(index int, val uint64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint64 uses the specified function to replace each uint64s -// by iterating each item. The data in the returned result will be a -// []uint64 containing the replaced items. -func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { - - arr := v.MustUint64Slice() - replaced := make([]uint64, len(arr)) - - v.EachUint64(func(index int, val uint64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint64 uses the specified collector function to collect a value -// for each of the uint64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { - - arr := v.MustUint64Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint64(func(index int, val uint64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uintptr (uintptr and []uintptr) - -------------------------------------------------- -*/ - -// Uintptr gets the value as a uintptr, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { - if s, ok := v.data.(uintptr); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUintptr gets the value as a uintptr. -// -// Panics if the object is not a uintptr. -func (v *Value) MustUintptr() uintptr { - return v.data.(uintptr) -} - -// UintptrSlice gets the value as a []uintptr, returns the optionalDefault -// value or nil if the value is not a []uintptr. -func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { - if s, ok := v.data.([]uintptr); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUintptrSlice gets the value as a []uintptr. -// -// Panics if the object is not a []uintptr. -func (v *Value) MustUintptrSlice() []uintptr { - return v.data.([]uintptr) -} - -// IsUintptr gets whether the object contained is a uintptr or not. -func (v *Value) IsUintptr() bool { - _, ok := v.data.(uintptr) - return ok -} - -// IsUintptrSlice gets whether the object contained is a []uintptr or not. -func (v *Value) IsUintptrSlice() bool { - _, ok := v.data.([]uintptr) - return ok -} - -// EachUintptr calls the specified callback for each object -// in the []uintptr. -// -// Panics if the object is the wrong type. -func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { - - for index, val := range v.MustUintptrSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUintptr uses the specified decider function to select items -// from the []uintptr. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { - - var selected []uintptr - - v.EachUintptr(func(index int, val uintptr) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUintptr uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uintptr. -func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { - - groups := make(map[string][]uintptr) - - v.EachUintptr(func(index int, val uintptr) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uintptr, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUintptr uses the specified function to replace each uintptrs -// by iterating each item. The data in the returned result will be a -// []uintptr containing the replaced items. -func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { - - arr := v.MustUintptrSlice() - replaced := make([]uintptr, len(arr)) - - v.EachUintptr(func(index int, val uintptr) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUintptr uses the specified collector function to collect a value -// for each of the uintptrs in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { - - arr := v.MustUintptrSlice() - collected := make([]interface{}, len(arr)) - - v.EachUintptr(func(index int, val uintptr) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Float32 (float32 and []float32) - -------------------------------------------------- -*/ - -// Float32 gets the value as a float32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Float32(optionalDefault ...float32) float32 { - if s, ok := v.data.(float32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustFloat32 gets the value as a float32. -// -// Panics if the object is not a float32. -func (v *Value) MustFloat32() float32 { - return v.data.(float32) -} - -// Float32Slice gets the value as a []float32, returns the optionalDefault -// value or nil if the value is not a []float32. -func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { - if s, ok := v.data.([]float32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustFloat32Slice gets the value as a []float32. -// -// Panics if the object is not a []float32. -func (v *Value) MustFloat32Slice() []float32 { - return v.data.([]float32) -} - -// IsFloat32 gets whether the object contained is a float32 or not. -func (v *Value) IsFloat32() bool { - _, ok := v.data.(float32) - return ok -} - -// IsFloat32Slice gets whether the object contained is a []float32 or not. -func (v *Value) IsFloat32Slice() bool { - _, ok := v.data.([]float32) - return ok -} - -// EachFloat32 calls the specified callback for each object -// in the []float32. -// -// Panics if the object is the wrong type. -func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { - - for index, val := range v.MustFloat32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereFloat32 uses the specified decider function to select items -// from the []float32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { - - var selected []float32 - - v.EachFloat32(func(index int, val float32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupFloat32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]float32. -func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { - - groups := make(map[string][]float32) - - v.EachFloat32(func(index int, val float32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]float32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceFloat32 uses the specified function to replace each float32s -// by iterating each item. The data in the returned result will be a -// []float32 containing the replaced items. -func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { - - arr := v.MustFloat32Slice() - replaced := make([]float32, len(arr)) - - v.EachFloat32(func(index int, val float32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectFloat32 uses the specified collector function to collect a value -// for each of the float32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { - - arr := v.MustFloat32Slice() - collected := make([]interface{}, len(arr)) - - v.EachFloat32(func(index int, val float32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Float64 (float64 and []float64) - -------------------------------------------------- -*/ - -// Float64 gets the value as a float64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Float64(optionalDefault ...float64) float64 { - if s, ok := v.data.(float64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustFloat64 gets the value as a float64. -// -// Panics if the object is not a float64. -func (v *Value) MustFloat64() float64 { - return v.data.(float64) -} - -// Float64Slice gets the value as a []float64, returns the optionalDefault -// value or nil if the value is not a []float64. -func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { - if s, ok := v.data.([]float64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustFloat64Slice gets the value as a []float64. -// -// Panics if the object is not a []float64. -func (v *Value) MustFloat64Slice() []float64 { - return v.data.([]float64) -} - -// IsFloat64 gets whether the object contained is a float64 or not. -func (v *Value) IsFloat64() bool { - _, ok := v.data.(float64) - return ok -} - -// IsFloat64Slice gets whether the object contained is a []float64 or not. -func (v *Value) IsFloat64Slice() bool { - _, ok := v.data.([]float64) - return ok -} - -// EachFloat64 calls the specified callback for each object -// in the []float64. -// -// Panics if the object is the wrong type. -func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { - - for index, val := range v.MustFloat64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereFloat64 uses the specified decider function to select items -// from the []float64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { - - var selected []float64 - - v.EachFloat64(func(index int, val float64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupFloat64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]float64. -func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { - - groups := make(map[string][]float64) - - v.EachFloat64(func(index int, val float64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]float64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceFloat64 uses the specified function to replace each float64s -// by iterating each item. The data in the returned result will be a -// []float64 containing the replaced items. -func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { - - arr := v.MustFloat64Slice() - replaced := make([]float64, len(arr)) - - v.EachFloat64(func(index int, val float64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectFloat64 uses the specified collector function to collect a value -// for each of the float64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { - - arr := v.MustFloat64Slice() - collected := make([]interface{}, len(arr)) - - v.EachFloat64(func(index int, val float64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Complex64 (complex64 and []complex64) - -------------------------------------------------- -*/ - -// Complex64 gets the value as a complex64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Complex64(optionalDefault ...complex64) complex64 { - if s, ok := v.data.(complex64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustComplex64 gets the value as a complex64. -// -// Panics if the object is not a complex64. -func (v *Value) MustComplex64() complex64 { - return v.data.(complex64) -} - -// Complex64Slice gets the value as a []complex64, returns the optionalDefault -// value or nil if the value is not a []complex64. -func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { - if s, ok := v.data.([]complex64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustComplex64Slice gets the value as a []complex64. -// -// Panics if the object is not a []complex64. -func (v *Value) MustComplex64Slice() []complex64 { - return v.data.([]complex64) -} - -// IsComplex64 gets whether the object contained is a complex64 or not. -func (v *Value) IsComplex64() bool { - _, ok := v.data.(complex64) - return ok -} - -// IsComplex64Slice gets whether the object contained is a []complex64 or not. -func (v *Value) IsComplex64Slice() bool { - _, ok := v.data.([]complex64) - return ok -} - -// EachComplex64 calls the specified callback for each object -// in the []complex64. -// -// Panics if the object is the wrong type. -func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { - - for index, val := range v.MustComplex64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereComplex64 uses the specified decider function to select items -// from the []complex64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { - - var selected []complex64 - - v.EachComplex64(func(index int, val complex64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupComplex64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]complex64. -func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { - - groups := make(map[string][]complex64) - - v.EachComplex64(func(index int, val complex64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]complex64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceComplex64 uses the specified function to replace each complex64s -// by iterating each item. The data in the returned result will be a -// []complex64 containing the replaced items. -func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { - - arr := v.MustComplex64Slice() - replaced := make([]complex64, len(arr)) - - v.EachComplex64(func(index int, val complex64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectComplex64 uses the specified collector function to collect a value -// for each of the complex64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { - - arr := v.MustComplex64Slice() - collected := make([]interface{}, len(arr)) - - v.EachComplex64(func(index int, val complex64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Complex128 (complex128 and []complex128) - -------------------------------------------------- -*/ - -// Complex128 gets the value as a complex128, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Complex128(optionalDefault ...complex128) complex128 { - if s, ok := v.data.(complex128); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustComplex128 gets the value as a complex128. -// -// Panics if the object is not a complex128. -func (v *Value) MustComplex128() complex128 { - return v.data.(complex128) -} - -// Complex128Slice gets the value as a []complex128, returns the optionalDefault -// value or nil if the value is not a []complex128. -func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { - if s, ok := v.data.([]complex128); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustComplex128Slice gets the value as a []complex128. -// -// Panics if the object is not a []complex128. -func (v *Value) MustComplex128Slice() []complex128 { - return v.data.([]complex128) -} - -// IsComplex128 gets whether the object contained is a complex128 or not. -func (v *Value) IsComplex128() bool { - _, ok := v.data.(complex128) - return ok -} - -// IsComplex128Slice gets whether the object contained is a []complex128 or not. -func (v *Value) IsComplex128Slice() bool { - _, ok := v.data.([]complex128) - return ok -} - -// EachComplex128 calls the specified callback for each object -// in the []complex128. -// -// Panics if the object is the wrong type. -func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { - - for index, val := range v.MustComplex128Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereComplex128 uses the specified decider function to select items -// from the []complex128. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { - - var selected []complex128 - - v.EachComplex128(func(index int, val complex128) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupComplex128 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]complex128. -func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { - - groups := make(map[string][]complex128) - - v.EachComplex128(func(index int, val complex128) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]complex128, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceComplex128 uses the specified function to replace each complex128s -// by iterating each item. The data in the returned result will be a -// []complex128 containing the replaced items. -func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { - - arr := v.MustComplex128Slice() - replaced := make([]complex128, len(arr)) - - v.EachComplex128(func(index int, val complex128) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectComplex128 uses the specified collector function to collect a value -// for each of the complex128s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { - - arr := v.MustComplex128Slice() - collected := make([]interface{}, len(arr)) - - v.EachComplex128(func(index int, val complex128) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go deleted file mode 100644 index f7a4fcee..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go +++ /dev/null @@ -1,2867 +0,0 @@ -package objx - -import ( - "fmt" - "github.com/stretchr/testify/assert" - "testing" -) - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInter(t *testing.T) { - - val := interface{}("something") - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Inter()) - assert.Equal(t, val, New(m).Get("value").MustInter()) - assert.Equal(t, interface{}(nil), New(m).Get("nothing").Inter()) - assert.Equal(t, val, New(m).Get("nothing").Inter("something")) - - assert.Panics(t, func() { - New(m).Get("age").MustInter() - }) - -} - -func TestInterSlice(t *testing.T) { - - val := interface{}("something") - m := map[string]interface{}{"value": []interface{}{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").InterSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInterSlice()[0]) - assert.Equal(t, []interface{}(nil), New(m).Get("nothing").InterSlice()) - assert.Equal(t, val, New(m).Get("nothing").InterSlice([]interface{}{interface{}("something")})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInterSlice() - }) - -} - -func TestIsInter(t *testing.T) { - - var v *Value - - v = &Value{data: interface{}("something")} - assert.True(t, v.IsInter()) - - v = &Value{data: []interface{}{interface{}("something")}} - assert.True(t, v.IsInterSlice()) - -} - -func TestEachInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - count := 0 - replacedVals := make([]interface{}, 0) - assert.Equal(t, v, v.EachInter(func(i int, val interface{}) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInterSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustInterSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustInterSlice()[2]) - -} - -func TestWhereInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - selected := v.WhereInter(func(i int, val interface{}) bool { - return i%2 == 0 - }).MustInterSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - grouped := v.GroupInter(func(i int, val interface{}) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]interface{}) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - rawArr := v.MustInterSlice() - - replaced := v.ReplaceInter(func(index int, val interface{}) interface{} { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInterSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - collected := v.CollectInter(func(index int, val interface{}) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestMSI(t *testing.T) { - - val := map[string]interface{}(map[string]interface{}{"name": "Tyler"}) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").MSI()) - assert.Equal(t, val, New(m).Get("value").MustMSI()) - assert.Equal(t, map[string]interface{}(nil), New(m).Get("nothing").MSI()) - assert.Equal(t, val, New(m).Get("nothing").MSI(map[string]interface{}{"name": "Tyler"})) - - assert.Panics(t, func() { - New(m).Get("age").MustMSI() - }) - -} - -func TestMSISlice(t *testing.T) { - - val := map[string]interface{}(map[string]interface{}{"name": "Tyler"}) - m := map[string]interface{}{"value": []map[string]interface{}{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").MSISlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustMSISlice()[0]) - assert.Equal(t, []map[string]interface{}(nil), New(m).Get("nothing").MSISlice()) - assert.Equal(t, val, New(m).Get("nothing").MSISlice([]map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"})})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustMSISlice() - }) - -} - -func TestIsMSI(t *testing.T) { - - var v *Value - - v = &Value{data: map[string]interface{}(map[string]interface{}{"name": "Tyler"})} - assert.True(t, v.IsMSI()) - - v = &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - assert.True(t, v.IsMSISlice()) - -} - -func TestEachMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - count := 0 - replacedVals := make([]map[string]interface{}, 0) - assert.Equal(t, v, v.EachMSI(func(i int, val map[string]interface{}) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustMSISlice()[0]) - assert.Equal(t, replacedVals[1], v.MustMSISlice()[1]) - assert.Equal(t, replacedVals[2], v.MustMSISlice()[2]) - -} - -func TestWhereMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - selected := v.WhereMSI(func(i int, val map[string]interface{}) bool { - return i%2 == 0 - }).MustMSISlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - grouped := v.GroupMSI(func(i int, val map[string]interface{}) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]map[string]interface{}) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - rawArr := v.MustMSISlice() - - replaced := v.ReplaceMSI(func(index int, val map[string]interface{}) map[string]interface{} { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustMSISlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - collected := v.CollectMSI(func(index int, val map[string]interface{}) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestObjxMap(t *testing.T) { - - val := (Map)(New(1)) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").ObjxMap()) - assert.Equal(t, val, New(m).Get("value").MustObjxMap()) - assert.Equal(t, (Map)(New(nil)), New(m).Get("nothing").ObjxMap()) - assert.Equal(t, val, New(m).Get("nothing").ObjxMap(New(1))) - - assert.Panics(t, func() { - New(m).Get("age").MustObjxMap() - }) - -} - -func TestObjxMapSlice(t *testing.T) { - - val := (Map)(New(1)) - m := map[string]interface{}{"value": [](Map){val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").ObjxMapSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustObjxMapSlice()[0]) - assert.Equal(t, [](Map)(nil), New(m).Get("nothing").ObjxMapSlice()) - assert.Equal(t, val, New(m).Get("nothing").ObjxMapSlice([](Map){(Map)(New(1))})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustObjxMapSlice() - }) - -} - -func TestIsObjxMap(t *testing.T) { - - var v *Value - - v = &Value{data: (Map)(New(1))} - assert.True(t, v.IsObjxMap()) - - v = &Value{data: [](Map){(Map)(New(1))}} - assert.True(t, v.IsObjxMapSlice()) - -} - -func TestEachObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - count := 0 - replacedVals := make([](Map), 0) - assert.Equal(t, v, v.EachObjxMap(func(i int, val Map) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustObjxMapSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustObjxMapSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustObjxMapSlice()[2]) - -} - -func TestWhereObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - selected := v.WhereObjxMap(func(i int, val Map) bool { - return i%2 == 0 - }).MustObjxMapSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - grouped := v.GroupObjxMap(func(i int, val Map) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][](Map)) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - rawArr := v.MustObjxMapSlice() - - replaced := v.ReplaceObjxMap(func(index int, val Map) Map { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustObjxMapSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - collected := v.CollectObjxMap(func(index int, val Map) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestBool(t *testing.T) { - - val := bool(true) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Bool()) - assert.Equal(t, val, New(m).Get("value").MustBool()) - assert.Equal(t, bool(false), New(m).Get("nothing").Bool()) - assert.Equal(t, val, New(m).Get("nothing").Bool(true)) - - assert.Panics(t, func() { - New(m).Get("age").MustBool() - }) - -} - -func TestBoolSlice(t *testing.T) { - - val := bool(true) - m := map[string]interface{}{"value": []bool{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").BoolSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustBoolSlice()[0]) - assert.Equal(t, []bool(nil), New(m).Get("nothing").BoolSlice()) - assert.Equal(t, val, New(m).Get("nothing").BoolSlice([]bool{bool(true)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustBoolSlice() - }) - -} - -func TestIsBool(t *testing.T) { - - var v *Value - - v = &Value{data: bool(true)} - assert.True(t, v.IsBool()) - - v = &Value{data: []bool{bool(true)}} - assert.True(t, v.IsBoolSlice()) - -} - -func TestEachBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true)}} - count := 0 - replacedVals := make([]bool, 0) - assert.Equal(t, v, v.EachBool(func(i int, val bool) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustBoolSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustBoolSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustBoolSlice()[2]) - -} - -func TestWhereBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - selected := v.WhereBool(func(i int, val bool) bool { - return i%2 == 0 - }).MustBoolSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - grouped := v.GroupBool(func(i int, val bool) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]bool) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - rawArr := v.MustBoolSlice() - - replaced := v.ReplaceBool(func(index int, val bool) bool { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustBoolSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - collected := v.CollectBool(func(index int, val bool) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestStr(t *testing.T) { - - val := string("hello") - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Str()) - assert.Equal(t, val, New(m).Get("value").MustStr()) - assert.Equal(t, string(""), New(m).Get("nothing").Str()) - assert.Equal(t, val, New(m).Get("nothing").Str("hello")) - - assert.Panics(t, func() { - New(m).Get("age").MustStr() - }) - -} - -func TestStrSlice(t *testing.T) { - - val := string("hello") - m := map[string]interface{}{"value": []string{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").StrSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustStrSlice()[0]) - assert.Equal(t, []string(nil), New(m).Get("nothing").StrSlice()) - assert.Equal(t, val, New(m).Get("nothing").StrSlice([]string{string("hello")})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustStrSlice() - }) - -} - -func TestIsStr(t *testing.T) { - - var v *Value - - v = &Value{data: string("hello")} - assert.True(t, v.IsStr()) - - v = &Value{data: []string{string("hello")}} - assert.True(t, v.IsStrSlice()) - -} - -func TestEachStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - count := 0 - replacedVals := make([]string, 0) - assert.Equal(t, v, v.EachStr(func(i int, val string) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustStrSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustStrSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustStrSlice()[2]) - -} - -func TestWhereStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - selected := v.WhereStr(func(i int, val string) bool { - return i%2 == 0 - }).MustStrSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - grouped := v.GroupStr(func(i int, val string) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]string) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - rawArr := v.MustStrSlice() - - replaced := v.ReplaceStr(func(index int, val string) string { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustStrSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - collected := v.CollectStr(func(index int, val string) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt(t *testing.T) { - - val := int(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int()) - assert.Equal(t, val, New(m).Get("value").MustInt()) - assert.Equal(t, int(0), New(m).Get("nothing").Int()) - assert.Equal(t, val, New(m).Get("nothing").Int(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt() - }) - -} - -func TestIntSlice(t *testing.T) { - - val := int(1) - m := map[string]interface{}{"value": []int{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").IntSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustIntSlice()[0]) - assert.Equal(t, []int(nil), New(m).Get("nothing").IntSlice()) - assert.Equal(t, val, New(m).Get("nothing").IntSlice([]int{int(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustIntSlice() - }) - -} - -func TestIsInt(t *testing.T) { - - var v *Value - - v = &Value{data: int(1)} - assert.True(t, v.IsInt()) - - v = &Value{data: []int{int(1)}} - assert.True(t, v.IsIntSlice()) - -} - -func TestEachInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1)}} - count := 0 - replacedVals := make([]int, 0) - assert.Equal(t, v, v.EachInt(func(i int, val int) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustIntSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustIntSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustIntSlice()[2]) - -} - -func TestWhereInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - selected := v.WhereInt(func(i int, val int) bool { - return i%2 == 0 - }).MustIntSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - grouped := v.GroupInt(func(i int, val int) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - rawArr := v.MustIntSlice() - - replaced := v.ReplaceInt(func(index int, val int) int { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustIntSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - collected := v.CollectInt(func(index int, val int) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt8(t *testing.T) { - - val := int8(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int8()) - assert.Equal(t, val, New(m).Get("value").MustInt8()) - assert.Equal(t, int8(0), New(m).Get("nothing").Int8()) - assert.Equal(t, val, New(m).Get("nothing").Int8(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt8() - }) - -} - -func TestInt8Slice(t *testing.T) { - - val := int8(1) - m := map[string]interface{}{"value": []int8{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int8Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt8Slice()[0]) - assert.Equal(t, []int8(nil), New(m).Get("nothing").Int8Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int8Slice([]int8{int8(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt8Slice() - }) - -} - -func TestIsInt8(t *testing.T) { - - var v *Value - - v = &Value{data: int8(1)} - assert.True(t, v.IsInt8()) - - v = &Value{data: []int8{int8(1)}} - assert.True(t, v.IsInt8Slice()) - -} - -func TestEachInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1)}} - count := 0 - replacedVals := make([]int8, 0) - assert.Equal(t, v, v.EachInt8(func(i int, val int8) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt8Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt8Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt8Slice()[2]) - -} - -func TestWhereInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - selected := v.WhereInt8(func(i int, val int8) bool { - return i%2 == 0 - }).MustInt8Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - grouped := v.GroupInt8(func(i int, val int8) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int8) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - rawArr := v.MustInt8Slice() - - replaced := v.ReplaceInt8(func(index int, val int8) int8 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt8Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - collected := v.CollectInt8(func(index int, val int8) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt16(t *testing.T) { - - val := int16(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int16()) - assert.Equal(t, val, New(m).Get("value").MustInt16()) - assert.Equal(t, int16(0), New(m).Get("nothing").Int16()) - assert.Equal(t, val, New(m).Get("nothing").Int16(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt16() - }) - -} - -func TestInt16Slice(t *testing.T) { - - val := int16(1) - m := map[string]interface{}{"value": []int16{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int16Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt16Slice()[0]) - assert.Equal(t, []int16(nil), New(m).Get("nothing").Int16Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int16Slice([]int16{int16(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt16Slice() - }) - -} - -func TestIsInt16(t *testing.T) { - - var v *Value - - v = &Value{data: int16(1)} - assert.True(t, v.IsInt16()) - - v = &Value{data: []int16{int16(1)}} - assert.True(t, v.IsInt16Slice()) - -} - -func TestEachInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1)}} - count := 0 - replacedVals := make([]int16, 0) - assert.Equal(t, v, v.EachInt16(func(i int, val int16) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt16Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt16Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt16Slice()[2]) - -} - -func TestWhereInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - selected := v.WhereInt16(func(i int, val int16) bool { - return i%2 == 0 - }).MustInt16Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - grouped := v.GroupInt16(func(i int, val int16) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int16) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - rawArr := v.MustInt16Slice() - - replaced := v.ReplaceInt16(func(index int, val int16) int16 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt16Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - collected := v.CollectInt16(func(index int, val int16) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt32(t *testing.T) { - - val := int32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int32()) - assert.Equal(t, val, New(m).Get("value").MustInt32()) - assert.Equal(t, int32(0), New(m).Get("nothing").Int32()) - assert.Equal(t, val, New(m).Get("nothing").Int32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt32() - }) - -} - -func TestInt32Slice(t *testing.T) { - - val := int32(1) - m := map[string]interface{}{"value": []int32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt32Slice()[0]) - assert.Equal(t, []int32(nil), New(m).Get("nothing").Int32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int32Slice([]int32{int32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt32Slice() - }) - -} - -func TestIsInt32(t *testing.T) { - - var v *Value - - v = &Value{data: int32(1)} - assert.True(t, v.IsInt32()) - - v = &Value{data: []int32{int32(1)}} - assert.True(t, v.IsInt32Slice()) - -} - -func TestEachInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1)}} - count := 0 - replacedVals := make([]int32, 0) - assert.Equal(t, v, v.EachInt32(func(i int, val int32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt32Slice()[2]) - -} - -func TestWhereInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - selected := v.WhereInt32(func(i int, val int32) bool { - return i%2 == 0 - }).MustInt32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - grouped := v.GroupInt32(func(i int, val int32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - rawArr := v.MustInt32Slice() - - replaced := v.ReplaceInt32(func(index int, val int32) int32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - collected := v.CollectInt32(func(index int, val int32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt64(t *testing.T) { - - val := int64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int64()) - assert.Equal(t, val, New(m).Get("value").MustInt64()) - assert.Equal(t, int64(0), New(m).Get("nothing").Int64()) - assert.Equal(t, val, New(m).Get("nothing").Int64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt64() - }) - -} - -func TestInt64Slice(t *testing.T) { - - val := int64(1) - m := map[string]interface{}{"value": []int64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt64Slice()[0]) - assert.Equal(t, []int64(nil), New(m).Get("nothing").Int64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int64Slice([]int64{int64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt64Slice() - }) - -} - -func TestIsInt64(t *testing.T) { - - var v *Value - - v = &Value{data: int64(1)} - assert.True(t, v.IsInt64()) - - v = &Value{data: []int64{int64(1)}} - assert.True(t, v.IsInt64Slice()) - -} - -func TestEachInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1)}} - count := 0 - replacedVals := make([]int64, 0) - assert.Equal(t, v, v.EachInt64(func(i int, val int64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt64Slice()[2]) - -} - -func TestWhereInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - selected := v.WhereInt64(func(i int, val int64) bool { - return i%2 == 0 - }).MustInt64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - grouped := v.GroupInt64(func(i int, val int64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - rawArr := v.MustInt64Slice() - - replaced := v.ReplaceInt64(func(index int, val int64) int64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - collected := v.CollectInt64(func(index int, val int64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint(t *testing.T) { - - val := uint(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint()) - assert.Equal(t, val, New(m).Get("value").MustUint()) - assert.Equal(t, uint(0), New(m).Get("nothing").Uint()) - assert.Equal(t, val, New(m).Get("nothing").Uint(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint() - }) - -} - -func TestUintSlice(t *testing.T) { - - val := uint(1) - m := map[string]interface{}{"value": []uint{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").UintSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUintSlice()[0]) - assert.Equal(t, []uint(nil), New(m).Get("nothing").UintSlice()) - assert.Equal(t, val, New(m).Get("nothing").UintSlice([]uint{uint(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUintSlice() - }) - -} - -func TestIsUint(t *testing.T) { - - var v *Value - - v = &Value{data: uint(1)} - assert.True(t, v.IsUint()) - - v = &Value{data: []uint{uint(1)}} - assert.True(t, v.IsUintSlice()) - -} - -func TestEachUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1)}} - count := 0 - replacedVals := make([]uint, 0) - assert.Equal(t, v, v.EachUint(func(i int, val uint) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUintSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustUintSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustUintSlice()[2]) - -} - -func TestWhereUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - selected := v.WhereUint(func(i int, val uint) bool { - return i%2 == 0 - }).MustUintSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - grouped := v.GroupUint(func(i int, val uint) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - rawArr := v.MustUintSlice() - - replaced := v.ReplaceUint(func(index int, val uint) uint { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUintSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - collected := v.CollectUint(func(index int, val uint) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint8(t *testing.T) { - - val := uint8(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint8()) - assert.Equal(t, val, New(m).Get("value").MustUint8()) - assert.Equal(t, uint8(0), New(m).Get("nothing").Uint8()) - assert.Equal(t, val, New(m).Get("nothing").Uint8(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint8() - }) - -} - -func TestUint8Slice(t *testing.T) { - - val := uint8(1) - m := map[string]interface{}{"value": []uint8{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint8Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint8Slice()[0]) - assert.Equal(t, []uint8(nil), New(m).Get("nothing").Uint8Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint8Slice([]uint8{uint8(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint8Slice() - }) - -} - -func TestIsUint8(t *testing.T) { - - var v *Value - - v = &Value{data: uint8(1)} - assert.True(t, v.IsUint8()) - - v = &Value{data: []uint8{uint8(1)}} - assert.True(t, v.IsUint8Slice()) - -} - -func TestEachUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - count := 0 - replacedVals := make([]uint8, 0) - assert.Equal(t, v, v.EachUint8(func(i int, val uint8) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint8Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint8Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint8Slice()[2]) - -} - -func TestWhereUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - selected := v.WhereUint8(func(i int, val uint8) bool { - return i%2 == 0 - }).MustUint8Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - grouped := v.GroupUint8(func(i int, val uint8) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint8) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - rawArr := v.MustUint8Slice() - - replaced := v.ReplaceUint8(func(index int, val uint8) uint8 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint8Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - collected := v.CollectUint8(func(index int, val uint8) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint16(t *testing.T) { - - val := uint16(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint16()) - assert.Equal(t, val, New(m).Get("value").MustUint16()) - assert.Equal(t, uint16(0), New(m).Get("nothing").Uint16()) - assert.Equal(t, val, New(m).Get("nothing").Uint16(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint16() - }) - -} - -func TestUint16Slice(t *testing.T) { - - val := uint16(1) - m := map[string]interface{}{"value": []uint16{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint16Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint16Slice()[0]) - assert.Equal(t, []uint16(nil), New(m).Get("nothing").Uint16Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint16Slice([]uint16{uint16(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint16Slice() - }) - -} - -func TestIsUint16(t *testing.T) { - - var v *Value - - v = &Value{data: uint16(1)} - assert.True(t, v.IsUint16()) - - v = &Value{data: []uint16{uint16(1)}} - assert.True(t, v.IsUint16Slice()) - -} - -func TestEachUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - count := 0 - replacedVals := make([]uint16, 0) - assert.Equal(t, v, v.EachUint16(func(i int, val uint16) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint16Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint16Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint16Slice()[2]) - -} - -func TestWhereUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - selected := v.WhereUint16(func(i int, val uint16) bool { - return i%2 == 0 - }).MustUint16Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - grouped := v.GroupUint16(func(i int, val uint16) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint16) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - rawArr := v.MustUint16Slice() - - replaced := v.ReplaceUint16(func(index int, val uint16) uint16 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint16Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - collected := v.CollectUint16(func(index int, val uint16) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint32(t *testing.T) { - - val := uint32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint32()) - assert.Equal(t, val, New(m).Get("value").MustUint32()) - assert.Equal(t, uint32(0), New(m).Get("nothing").Uint32()) - assert.Equal(t, val, New(m).Get("nothing").Uint32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint32() - }) - -} - -func TestUint32Slice(t *testing.T) { - - val := uint32(1) - m := map[string]interface{}{"value": []uint32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint32Slice()[0]) - assert.Equal(t, []uint32(nil), New(m).Get("nothing").Uint32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint32Slice([]uint32{uint32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint32Slice() - }) - -} - -func TestIsUint32(t *testing.T) { - - var v *Value - - v = &Value{data: uint32(1)} - assert.True(t, v.IsUint32()) - - v = &Value{data: []uint32{uint32(1)}} - assert.True(t, v.IsUint32Slice()) - -} - -func TestEachUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - count := 0 - replacedVals := make([]uint32, 0) - assert.Equal(t, v, v.EachUint32(func(i int, val uint32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint32Slice()[2]) - -} - -func TestWhereUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - selected := v.WhereUint32(func(i int, val uint32) bool { - return i%2 == 0 - }).MustUint32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - grouped := v.GroupUint32(func(i int, val uint32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - rawArr := v.MustUint32Slice() - - replaced := v.ReplaceUint32(func(index int, val uint32) uint32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - collected := v.CollectUint32(func(index int, val uint32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint64(t *testing.T) { - - val := uint64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint64()) - assert.Equal(t, val, New(m).Get("value").MustUint64()) - assert.Equal(t, uint64(0), New(m).Get("nothing").Uint64()) - assert.Equal(t, val, New(m).Get("nothing").Uint64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint64() - }) - -} - -func TestUint64Slice(t *testing.T) { - - val := uint64(1) - m := map[string]interface{}{"value": []uint64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint64Slice()[0]) - assert.Equal(t, []uint64(nil), New(m).Get("nothing").Uint64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint64Slice([]uint64{uint64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint64Slice() - }) - -} - -func TestIsUint64(t *testing.T) { - - var v *Value - - v = &Value{data: uint64(1)} - assert.True(t, v.IsUint64()) - - v = &Value{data: []uint64{uint64(1)}} - assert.True(t, v.IsUint64Slice()) - -} - -func TestEachUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - count := 0 - replacedVals := make([]uint64, 0) - assert.Equal(t, v, v.EachUint64(func(i int, val uint64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint64Slice()[2]) - -} - -func TestWhereUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - selected := v.WhereUint64(func(i int, val uint64) bool { - return i%2 == 0 - }).MustUint64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - grouped := v.GroupUint64(func(i int, val uint64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - rawArr := v.MustUint64Slice() - - replaced := v.ReplaceUint64(func(index int, val uint64) uint64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - collected := v.CollectUint64(func(index int, val uint64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUintptr(t *testing.T) { - - val := uintptr(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uintptr()) - assert.Equal(t, val, New(m).Get("value").MustUintptr()) - assert.Equal(t, uintptr(0), New(m).Get("nothing").Uintptr()) - assert.Equal(t, val, New(m).Get("nothing").Uintptr(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUintptr() - }) - -} - -func TestUintptrSlice(t *testing.T) { - - val := uintptr(1) - m := map[string]interface{}{"value": []uintptr{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").UintptrSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUintptrSlice()[0]) - assert.Equal(t, []uintptr(nil), New(m).Get("nothing").UintptrSlice()) - assert.Equal(t, val, New(m).Get("nothing").UintptrSlice([]uintptr{uintptr(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUintptrSlice() - }) - -} - -func TestIsUintptr(t *testing.T) { - - var v *Value - - v = &Value{data: uintptr(1)} - assert.True(t, v.IsUintptr()) - - v = &Value{data: []uintptr{uintptr(1)}} - assert.True(t, v.IsUintptrSlice()) - -} - -func TestEachUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - count := 0 - replacedVals := make([]uintptr, 0) - assert.Equal(t, v, v.EachUintptr(func(i int, val uintptr) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUintptrSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustUintptrSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustUintptrSlice()[2]) - -} - -func TestWhereUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - selected := v.WhereUintptr(func(i int, val uintptr) bool { - return i%2 == 0 - }).MustUintptrSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - grouped := v.GroupUintptr(func(i int, val uintptr) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uintptr) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - rawArr := v.MustUintptrSlice() - - replaced := v.ReplaceUintptr(func(index int, val uintptr) uintptr { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUintptrSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - collected := v.CollectUintptr(func(index int, val uintptr) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestFloat32(t *testing.T) { - - val := float32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float32()) - assert.Equal(t, val, New(m).Get("value").MustFloat32()) - assert.Equal(t, float32(0), New(m).Get("nothing").Float32()) - assert.Equal(t, val, New(m).Get("nothing").Float32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustFloat32() - }) - -} - -func TestFloat32Slice(t *testing.T) { - - val := float32(1) - m := map[string]interface{}{"value": []float32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustFloat32Slice()[0]) - assert.Equal(t, []float32(nil), New(m).Get("nothing").Float32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Float32Slice([]float32{float32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustFloat32Slice() - }) - -} - -func TestIsFloat32(t *testing.T) { - - var v *Value - - v = &Value{data: float32(1)} - assert.True(t, v.IsFloat32()) - - v = &Value{data: []float32{float32(1)}} - assert.True(t, v.IsFloat32Slice()) - -} - -func TestEachFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1)}} - count := 0 - replacedVals := make([]float32, 0) - assert.Equal(t, v, v.EachFloat32(func(i int, val float32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustFloat32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustFloat32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustFloat32Slice()[2]) - -} - -func TestWhereFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - selected := v.WhereFloat32(func(i int, val float32) bool { - return i%2 == 0 - }).MustFloat32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - grouped := v.GroupFloat32(func(i int, val float32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]float32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - rawArr := v.MustFloat32Slice() - - replaced := v.ReplaceFloat32(func(index int, val float32) float32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustFloat32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - collected := v.CollectFloat32(func(index int, val float32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestFloat64(t *testing.T) { - - val := float64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float64()) - assert.Equal(t, val, New(m).Get("value").MustFloat64()) - assert.Equal(t, float64(0), New(m).Get("nothing").Float64()) - assert.Equal(t, val, New(m).Get("nothing").Float64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustFloat64() - }) - -} - -func TestFloat64Slice(t *testing.T) { - - val := float64(1) - m := map[string]interface{}{"value": []float64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustFloat64Slice()[0]) - assert.Equal(t, []float64(nil), New(m).Get("nothing").Float64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Float64Slice([]float64{float64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustFloat64Slice() - }) - -} - -func TestIsFloat64(t *testing.T) { - - var v *Value - - v = &Value{data: float64(1)} - assert.True(t, v.IsFloat64()) - - v = &Value{data: []float64{float64(1)}} - assert.True(t, v.IsFloat64Slice()) - -} - -func TestEachFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1)}} - count := 0 - replacedVals := make([]float64, 0) - assert.Equal(t, v, v.EachFloat64(func(i int, val float64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustFloat64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustFloat64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustFloat64Slice()[2]) - -} - -func TestWhereFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - selected := v.WhereFloat64(func(i int, val float64) bool { - return i%2 == 0 - }).MustFloat64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - grouped := v.GroupFloat64(func(i int, val float64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]float64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - rawArr := v.MustFloat64Slice() - - replaced := v.ReplaceFloat64(func(index int, val float64) float64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustFloat64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - collected := v.CollectFloat64(func(index int, val float64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestComplex64(t *testing.T) { - - val := complex64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex64()) - assert.Equal(t, val, New(m).Get("value").MustComplex64()) - assert.Equal(t, complex64(0), New(m).Get("nothing").Complex64()) - assert.Equal(t, val, New(m).Get("nothing").Complex64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustComplex64() - }) - -} - -func TestComplex64Slice(t *testing.T) { - - val := complex64(1) - m := map[string]interface{}{"value": []complex64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustComplex64Slice()[0]) - assert.Equal(t, []complex64(nil), New(m).Get("nothing").Complex64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Complex64Slice([]complex64{complex64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustComplex64Slice() - }) - -} - -func TestIsComplex64(t *testing.T) { - - var v *Value - - v = &Value{data: complex64(1)} - assert.True(t, v.IsComplex64()) - - v = &Value{data: []complex64{complex64(1)}} - assert.True(t, v.IsComplex64Slice()) - -} - -func TestEachComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - count := 0 - replacedVals := make([]complex64, 0) - assert.Equal(t, v, v.EachComplex64(func(i int, val complex64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustComplex64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustComplex64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustComplex64Slice()[2]) - -} - -func TestWhereComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - selected := v.WhereComplex64(func(i int, val complex64) bool { - return i%2 == 0 - }).MustComplex64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - grouped := v.GroupComplex64(func(i int, val complex64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]complex64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - rawArr := v.MustComplex64Slice() - - replaced := v.ReplaceComplex64(func(index int, val complex64) complex64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustComplex64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - collected := v.CollectComplex64(func(index int, val complex64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestComplex128(t *testing.T) { - - val := complex128(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex128()) - assert.Equal(t, val, New(m).Get("value").MustComplex128()) - assert.Equal(t, complex128(0), New(m).Get("nothing").Complex128()) - assert.Equal(t, val, New(m).Get("nothing").Complex128(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustComplex128() - }) - -} - -func TestComplex128Slice(t *testing.T) { - - val := complex128(1) - m := map[string]interface{}{"value": []complex128{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex128Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustComplex128Slice()[0]) - assert.Equal(t, []complex128(nil), New(m).Get("nothing").Complex128Slice()) - assert.Equal(t, val, New(m).Get("nothing").Complex128Slice([]complex128{complex128(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustComplex128Slice() - }) - -} - -func TestIsComplex128(t *testing.T) { - - var v *Value - - v = &Value{data: complex128(1)} - assert.True(t, v.IsComplex128()) - - v = &Value{data: []complex128{complex128(1)}} - assert.True(t, v.IsComplex128Slice()) - -} - -func TestEachComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - count := 0 - replacedVals := make([]complex128, 0) - assert.Equal(t, v, v.EachComplex128(func(i int, val complex128) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustComplex128Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustComplex128Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustComplex128Slice()[2]) - -} - -func TestWhereComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - selected := v.WhereComplex128(func(i int, val complex128) bool { - return i%2 == 0 - }).MustComplex128Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - grouped := v.GroupComplex128(func(i int, val complex128) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]complex128) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - rawArr := v.MustComplex128Slice() - - replaced := v.ReplaceComplex128(func(index int, val complex128) complex128 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustComplex128Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - collected := v.CollectComplex128(func(index int, val complex128) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/value.go b/Godeps/_workspace/src/github.com/stretchr/objx/value.go deleted file mode 100644 index 7aaef06b..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/value.go +++ /dev/null @@ -1,13 +0,0 @@ -package objx - -// Value provides methods for extracting interface{} data in various -// types. -type Value struct { - // data contains the raw data being managed by this Value - data interface{} -} - -// Data returns the raw data contained by this Value -func (v *Value) Data() interface{} { - return v.data -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go deleted file mode 100644 index 0bc65d92..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go +++ /dev/null @@ -1 +0,0 @@ -package objx diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index 58e17816..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,805 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "fmt" - "reflect" - "regexp" - "runtime" - "strings" - "time" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - - if expected == nil || actual == nil { - return expected == actual - } - - if reflect.DeepEqual(expected, actual) { - return true - } - - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return true - } - - return false - -} - -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - expectedValue := reflect.ValueOf(expected) - if expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { - return true - } - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occured in calling code.*/ - -// CallerInfo returns a string containing the file and line number of the assert call -// that failed. -func CallerInfo() string { - - file := "" - line := 0 - ok := false - - for i := 0; ; i++ { - _, file, line, ok = runtime.Caller(i) - if !ok { - return "" - } - parts := strings.Split(file, "/") - dir := parts[len(parts)-2] - file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - break - } - } - - return fmt.Sprintf("%s:%d", file, line) -} - -// getWhitespaceString returns a string that is long enough to overwrite the default -// output from the go testing framework. -func getWhitespaceString() string { - - _, file, line, ok := runtime.Caller(1) - if !ok { - return "" - } - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - - return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) - -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's -// test printing (see inner comment for specifics) -func indentMessageLines(message string, tabs int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - if i != 0 { - outBuf.WriteRune('\n') - } - for ii := 0; ii < tabs; ii++ { - outBuf.WriteRune('\t') - // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter - // by 1 prematurely. - if ii == 0 && i > 0 { - ii++ - } - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - - if len(message) > 0 { - t.Errorf("\r%s\r\tLocation:\t%s\n"+ - "\r\tError:%s\n"+ - "\r\tMessages:\t%s\n\r", - getWhitespaceString(), - CallerInfo(), - indentMessageLines(failureMessage, 2), - message) - } else { - t.Errorf("\r%s\r\tLocation:\t%s\n"+ - "\r\tError:%s\n\r", - getWhitespaceString(), - CallerInfo(), - indentMessageLines(failureMessage, 2)) - } - - return false -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...) - } - - return true - -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)", expected, actual), msgAndArgs...) - } - - return true - -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqualValues(expected, actual) { - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)", expected, actual), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - success := true - - if object == nil { - success = false - } else { - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - success = false - } - } - - if !success { - Fail(t, "Expected not to be nil.", msgAndArgs...) - } - - return success -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if isNil(object) { - return true - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -var zeros = []interface{}{ - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - float32(0), - float64(0), -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - if object == nil { - return true - } else if object == "" { - return true - } else if object == false { - return true - } - - for _, v := range zeros { - if object == v { - return true - } - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - case reflect.Map: - fallthrough - case reflect.Slice, reflect.Chan: - { - return (objValue.Len() == 0) - } - case reflect.Ptr: - { - switch object.(type) { - case *time.Time: - return object.(*time.Time).IsZero() - default: - return false - } - } - } - return false -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != true { - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is true. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != false { - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if ObjectsAreEqual(expected, actual) { - return Fail(t, "Should not be equal", msgAndArgs...) - } - - return true - -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string or list(array, slice...) contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string or list(array, slice...) does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// min(|expected|, |actual|) * epsilon -func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 { - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - // invalid input - return 0 - } - - if af < 0 { - af = -af - } - if bf < 0 { - bf = -bf - } - var delta float64 - if af < bf { - delta = af * epsilon - } else { - delta = bf * epsilon - } - return delta -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - delta := calcEpsilonDelta(expected, actual, epsilon) - - return InDelta(t, expected, actual, delta, msgAndArgs...) -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if isNil(err) { - return true - } - - return Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - return NotNil(t, err, "An error is expected but got nil. %s", message) - -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - if !NotNil(t, theError, "An error is expected but got nil. %s", message) { - return false - } - s := "An error with value \"%s\" is expected but got \"%s\". %s" - return Equal(t, theError.Error(), errString, - s, errString, theError.Error(), message) -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go deleted file mode 100644 index 2cb58dbd..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go +++ /dev/null @@ -1,768 +0,0 @@ -package assert - -import ( - "errors" - "regexp" - "testing" - "time" -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -func TestObjectsAreEqual(t *testing.T) { - - if !ObjectsAreEqual("Hello World", "Hello World") { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123, 123) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123.5, 123.5) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(nil, nil) { - t.Error("objectsAreEqual should return true") - } - if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual('x', "x") { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual("x", 'x') { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0, 0.1) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0.1, 0) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(uint32(10), int32(10)) { - t.Error("objectsAreEqual should return false") - } - if !ObjectsAreEqualValues(uint32(10), int32(10)) { - t.Error("ObjectsAreEqualValues should return true") - } - -} - -func TestImplements(t *testing.T) { - - mockT := new(testing.T) - - if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } - -} - -func TestIsType(t *testing.T) { - - mockT := new(testing.T) - - if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqual(t *testing.T) { - - mockT := new(testing.T) - - if !Equal(mockT, "Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !Equal(mockT, 123, 123) { - t.Error("Equal should return true") - } - if !Equal(mockT, 123.5, 123.5) { - t.Error("Equal should return true") - } - if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !Equal(mockT, nil, nil) { - t.Error("Equal should return true") - } - if !Equal(mockT, int32(123), int32(123)) { - t.Error("Equal should return true") - } - if !Equal(mockT, uint64(123), uint64(123)) { - t.Error("Equal should return true") - } - funcA := func() int { return 42 } - if !Equal(mockT, funcA, funcA) { - t.Error("Equal should return true") - } - -} - -func TestNotNil(t *testing.T) { - - mockT := new(testing.T) - - if !NotNil(mockT, new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if NotNil(mockT, nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNil(t *testing.T) { - - mockT := new(testing.T) - - if !Nil(mockT, nil) { - t.Error("Nil should return true: object is nil") - } - if Nil(mockT, new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrue(t *testing.T) { - - mockT := new(testing.T) - - if !True(mockT, true) { - t.Error("True should return true") - } - if True(mockT, false) { - t.Error("True should return false") - } - -} - -func TestFalse(t *testing.T) { - - mockT := new(testing.T) - - if !False(mockT, false) { - t.Error("False should return true") - } - if False(mockT, true) { - t.Error("False should return false") - } - -} - -func TestExactly(t *testing.T) { - - mockT := new(testing.T) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if Exactly(mockT, a, b) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, d) { - t.Error("Exactly should return false") - } - if !Exactly(mockT, a, c) { - t.Error("Exactly should return true") - } - - if Exactly(mockT, nil, a) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqual(t *testing.T) { - - mockT := new(testing.T) - - if !NotEqual(mockT, "Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123, 1234) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } - funcA := func() int { return 23 } - funcB := func() int { return 42 } - if !NotEqual(mockT, funcA, funcB) { - t.Error("NotEqual should return true") - } - - if NotEqual(mockT, "Hello World", "Hello World") { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123, 123) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123.5, 123.5) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return false") - } -} - -type A struct { - Name, Value string -} - -func TestContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - complexList := []*A{ - {"b", "c"}, - {"d", "e"}, - {"g", "h"}, - {"j", "k"}, - } - - if !Contains(mockT, "Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if Contains(mockT, "Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !Contains(mockT, list, "Bar") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") - } - if Contains(mockT, list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - if !Contains(mockT, complexList, &A{"g", "h"}) { - t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") - } - if Contains(mockT, complexList, &A{"g", "e"}) { - t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") - } -} - -func TestNotContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - - if !NotContains(mockT, "Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if NotContains(mockT, "Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !NotContains(mockT, list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if NotContains(mockT, list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func Test_includeElement(t *testing.T) { - - list1 := []string{"Foo", "Bar"} - list2 := []int{1, 2} - - ok, found := includeElement("Hello World", "World") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Bar") - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 1) - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 2) - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo!") - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, 3) - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, "1") - True(t, ok) - False(t, found) - - ok, found = includeElement(1433, "1") - False(t, ok) - False(t, found) - -} - -func TestCondition(t *testing.T) { - mockT := new(testing.T) - - if !Condition(mockT, func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if Condition(mockT, func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanic(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanics(t *testing.T) { - - mockT := new(testing.T) - - if !Panics(mockT, func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if Panics(mockT, func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanics(t *testing.T) { - - mockT := new(testing.T) - - if !NotPanics(mockT, func() { - }) { - t.Error("NotPanics should return true") - } - - if NotPanics(mockT, func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestEqual_Funcs(t *testing.T) { - - type f func() int - f1 := func() int { return 1 } - f2 := func() int { return 2 } - - f1Copy := f1 - - Equal(t, f1Copy, f1, "Funcs are the same and should be considered equal") - NotEqual(t, f1, f2, "f1 and f2 are different") - -} - -func TestNoError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - True(t, NoError(mockT, err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("some error") - - False(t, NoError(mockT, err), "NoError with error should return False") - -} - -func TestError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - False(t, Error(mockT, err), "Error should return False for nil arg") - - // now set an error - err = errors.New("some error") - - True(t, Error(mockT, err), "Error with error should return True") - -} - -func TestEqualError(t *testing.T) { - mockT := new(testing.T) - - // start with a nil error - var err error - False(t, EqualError(mockT, err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - False(t, EqualError(mockT, err, "Not some error"), - "EqualError should return false for different error string") - True(t, EqualError(mockT, err, "some error"), - "EqualError should return true") -} - -func Test_isEmpty(t *testing.T) { - - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, isEmpty("")) - True(t, isEmpty(nil)) - True(t, isEmpty([]string{})) - True(t, isEmpty(0)) - True(t, isEmpty(int32(0))) - True(t, isEmpty(int64(0))) - True(t, isEmpty(false)) - True(t, isEmpty(map[string]string{})) - True(t, isEmpty(new(time.Time))) - True(t, isEmpty(make(chan struct{}))) - False(t, isEmpty("something")) - False(t, isEmpty(errors.New("something"))) - False(t, isEmpty([]string{"something"})) - False(t, isEmpty(1)) - False(t, isEmpty(true)) - False(t, isEmpty(map[string]string{"Hello": "World"})) - False(t, isEmpty(chWithValue)) - -} - -func TestEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, Empty(mockT, ""), "Empty string is empty") - True(t, Empty(mockT, nil), "Nil is empty") - True(t, Empty(mockT, []string{}), "Empty string array is empty") - True(t, Empty(mockT, 0), "Zero int value is empty") - True(t, Empty(mockT, false), "False value is empty") - True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") - - False(t, Empty(mockT, "something"), "Non Empty string is not empty") - False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") - False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") - False(t, Empty(mockT, 1), "Non-zero int value is not empty") - False(t, Empty(mockT, true), "True value is not empty") - False(t, Empty(mockT, chWithValue), "Channel with values is not empty") -} - -func TestNotEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - False(t, NotEmpty(mockT, ""), "Empty string is empty") - False(t, NotEmpty(mockT, nil), "Nil is empty") - False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") - False(t, NotEmpty(mockT, 0), "Zero int value is empty") - False(t, NotEmpty(mockT, false), "False value is empty") - False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") - - True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") - True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") - True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") - True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") - True(t, NotEmpty(mockT, true), "True value is not empty") - True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") -} - -func Test_getLen(t *testing.T) { - falseCases := []interface{}{ - nil, - 0, - true, - false, - 'A', - struct{}{}, - } - for _, v := range falseCases { - ok, l := getLen(v) - False(t, ok, "Expected getLen fail to get length of %#v", v) - Equal(t, 0, l, "getLen should return 0 for %#v", v) - } - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - trueCases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range trueCases { - ok, l := getLen(c.v) - True(t, ok, "Expected getLen success to get length of %#v", c.v) - Equal(t, c.l, l) - } -} - -func TestLen(t *testing.T) { - mockT := new(testing.T) - - False(t, Len(mockT, nil, 0), "nil does not have length") - False(t, Len(mockT, 0, 0), "int does not have length") - False(t, Len(mockT, true, 0), "true does not have length") - False(t, Len(mockT, false, 0), "false does not have length") - False(t, Len(mockT, 'A', 0), "Rune does not have length") - False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } - - cases = []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 4}, - {[...]int{1, 2, 3}, 2}, - {"ABC", 2}, - {map[int]int{1: 2, 2: 4, 3: 6}, 4}, - {ch, 2}, - - {[]int{}, 1}, - {map[int]int{}, 1}, - {make(chan int), 1}, - - {[]int(nil), 1}, - {map[int]int(nil), 1}, - {(chan int)(nil), 1}, - } - - for _, c := range cases { - False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDuration(t *testing.T) { - - mockT := new(testing.T) - a := time.Now() - b := a.Add(10 * time.Second) - - True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDelta(t *testing.T) { - mockT := new(testing.T) - - True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") - False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInEpsilon(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - -} - -func TestRegexp(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, Regexp(mockT, tc.rx, tc.str)) - True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - False(t, NotRegexp(mockT, tc.rx, tc.str)) - False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - True(t, NotRegexp(mockT, tc.rx, tc.str)) - True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index 1c6de283..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,150 +0,0 @@ -// A set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -// -// Here is an overview of the assert functions: -// -// assert.Equal(t, expected, actual [, message [, format-args]) -// -// assert.NotEqual(t, notExpected, actual [, message [, format-args]]) -// -// assert.True(t, actualBool [, message [, format-args]]) -// -// assert.False(t, actualBool [, message [, format-args]]) -// -// assert.Nil(t, actualObject [, message [, format-args]]) -// -// assert.NotNil(t, actualObject [, message [, format-args]]) -// -// assert.Empty(t, actualObject [, message [, format-args]]) -// -// assert.NotEmpty(t, actualObject [, message [, format-args]]) -// -// assert.Len(t, actualObject, expectedLength, [, message [, format-args]]) -// -// assert.Error(t, errorObject [, message [, format-args]]) -// -// assert.NoError(t, errorObject [, message [, format-args]]) -// -// assert.EqualError(t, theError, errString [, message [, format-args]]) -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) -// -// assert.IsType(t, expectedObject, actualObject [, message [, format-args]]) -// -// assert.Contains(t, stringOrSlice, substringOrElement [, message [, format-args]]) -// -// assert.NotContains(t, stringOrSlice, substringOrElement [, message [, format-args]]) -// -// assert.Panics(t, func(){ -// -// // call code that should panic -// -// } [, message [, format-args]]) -// -// assert.NotPanics(t, func(){ -// -// // call code that should not panic -// -// } [, message [, format-args]]) -// -// assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) -// -// assert.InDelta(t, numA, numB, delta, [, message [, format-args]]) -// -// assert.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) -// -// assert package contains Assertions object. it has assertion methods. -// -// Here is an overview of the assert functions: -// assert.Equal(expected, actual [, message [, format-args]) -// -// assert.NotEqual(notExpected, actual [, message [, format-args]]) -// -// assert.True(actualBool [, message [, format-args]]) -// -// assert.False(actualBool [, message [, format-args]]) -// -// assert.Nil(actualObject [, message [, format-args]]) -// -// assert.NotNil(actualObject [, message [, format-args]]) -// -// assert.Empty(actualObject [, message [, format-args]]) -// -// assert.NotEmpty(actualObject [, message [, format-args]]) -// -// assert.Len(actualObject, expectedLength, [, message [, format-args]]) -// -// assert.Error(errorObject [, message [, format-args]]) -// -// assert.NoError(errorObject [, message [, format-args]]) -// -// assert.EqualError(theError, errString [, message [, format-args]]) -// -// assert.Implements((*MyInterface)(nil), new(MyObject) [,message [, format-args]]) -// -// assert.IsType(expectedObject, actualObject [, message [, format-args]]) -// -// assert.Contains(stringOrSlice, substringOrElement [, message [, format-args]]) -// -// assert.NotContains(stringOrSlice, substringOrElement [, message [, format-args]]) -// -// assert.Panics(func(){ -// -// // call code that should panic -// -// } [, message [, format-args]]) -// -// assert.NotPanics(func(){ -// -// // call code that should not panic -// -// } [, message [, format-args]]) -// -// assert.WithinDuration(timeA, timeB, deltaTime, [, message [, format-args]]) -// -// assert.InDelta(numA, numB, delta, [, message [, format-args]]) -// -// assert.InEpsilon(numA, numB, epsilon, [, message [, format-args]]) -package assert diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d1..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index 67a6925a..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,262 +0,0 @@ -package assert - -import "time" - -type Assertions struct { - t TestingT -} - -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - return Fail(a.t, failureMessage, msgAndArgs...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return IsType(a.t, expectedType, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return Exactly(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - return NotNil(a.t, object, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - return Nil(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a -// slice with len == 0. -// -// assert.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - return Empty(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a -// slice with len == 0. -// -// if assert.NotEmpty(obj) { -// assert.Equal("two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - return NotEmpty(a.t, object, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - return Len(a.t, object, length, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// assert.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - return True(a.t, value, msgAndArgs...) -} - -// False asserts that the specified value is true. -// -// assert.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - return False(a.t, value, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// Contains asserts that the specified string contains the specified substring. -// -// assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) bool { - return Contains(a.t, s, contains, msgAndArgs...) -} - -// NotContains asserts that the specified string does NOT contain the specified substring. -// -// assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) bool { - return NotContains(a.t, s, contains, msgAndArgs...) -} - -// Uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - return Condition(a.t, comp, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return Panics(a.t, f, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return NotPanics(a.t, f, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(err) { -// assert.Equal(actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) bool { - return NoError(a.t, theError, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) bool { - return Error(a.t, theError, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - return EqualError(a.t, theError, errString, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return Regexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return NotRegexp(a.t, rx, str, msgAndArgs...) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go deleted file mode 100644 index 0dac6c7a..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go +++ /dev/null @@ -1,526 +0,0 @@ -package assert - -import ( - "errors" - "regexp" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } -} - -func TestIsTypeWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqualWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Equal("Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !assert.Equal(123, 123) { - t.Error("Equal should return true") - } - if !assert.Equal(123.5, 123.5) { - t.Error("Equal should return true") - } - if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !assert.Equal(nil, nil) { - t.Error("Equal should return true") - } -} - -func TestEqualValuesWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.EqualValues(uint32(10), int32(10)) { - t.Error("EqualValues should return true") - } -} - -func TestNotNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.NotNil(new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if assert.NotNil(nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Nil(nil) { - t.Error("Nil should return true: object is nil") - } - if assert.Nil(new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrueWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.True(true) { - t.Error("True should return true") - } - if assert.True(false) { - t.Error("True should return false") - } - -} - -func TestFalseWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.False(false) { - t.Error("False should return true") - } - if assert.False(true) { - t.Error("False should return false") - } - -} - -func TestExactlyWrapper(t *testing.T) { - assert := New(new(testing.T)) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if assert.Exactly(a, b) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, d) { - t.Error("Exactly should return false") - } - if !assert.Exactly(a, c) { - t.Error("Exactly should return true") - } - - if assert.Exactly(nil, a) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqualWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotEqual("Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123, 1234) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } -} - -func TestContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.Contains("Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if assert.Contains("Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !assert.Contains(list, "Foo") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - if assert.Contains(list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - -} - -func TestNotContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.NotContains("Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if assert.NotContains("Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !assert.NotContains(list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if assert.NotContains(list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func TestConditionWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Condition(func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if assert.Condition(func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanicWrapper(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Panics(func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if assert.Panics(func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotPanics(func() { - }) { - t.Error("NotPanics should return true") - } - - if assert.NotPanics(func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestEqualWrapper_Funcs(t *testing.T) { - - assert := New(t) - - type f func() int - var f1 f = func() int { return 1 } - var f2 f = func() int { return 2 } - - var f1_copy f = f1 - - assert.Equal(f1_copy, f1, "Funcs are the same and should be considered equal") - assert.NotEqual(f1, f2, "f1 and f2 are different") - -} - -func TestNoErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error = nil - - assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.False(mockAssert.NoError(err), "NoError with error should return False") - -} - -func TestErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error = nil - - assert.False(mockAssert.Error(err), "Error should return False for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.True(mockAssert.Error(err), "Error with error should return True") - -} - -func TestEqualErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - assert.False(mockAssert.EqualError(err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - assert.False(mockAssert.EqualError(err, "Not some error"), - "EqualError should return false for different error string") - assert.True(mockAssert.EqualError(err, "some error"), - "EqualError should return true") -} - -func TestEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.Empty(""), "Empty string is empty") - assert.True(mockAssert.Empty(nil), "Nil is empty") - assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") - assert.True(mockAssert.Empty(0), "Zero int value is empty") - assert.True(mockAssert.Empty(false), "False value is empty") - - assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") - assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") - assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") - assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") - assert.False(mockAssert.Empty(true), "True value is not empty") - -} - -func TestNotEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.NotEmpty(""), "Empty string is empty") - assert.False(mockAssert.NotEmpty(nil), "Nil is empty") - assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") - assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") - assert.False(mockAssert.NotEmpty(false), "False value is empty") - - assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") - assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") - assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") - assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") - assert.True(mockAssert.NotEmpty(true), "True value is not empty") - -} - -func TestLenWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.Len(nil, 0), "nil does not have length") - assert.False(mockAssert.Len(0, 0), "int does not have length") - assert.False(mockAssert.Len(true, 0), "true does not have length") - assert.False(mockAssert.Len(false, 0), "false does not have length") - assert.False(mockAssert.Len('A', 0), "Rune does not have length") - assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDurationWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - a := time.Now() - b := a.Add(10 * time.Second) - - assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDeltaWrapper(t *testing.T) { - assert := New(new(testing.T)) - - True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") - False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInEpsilonWrapper(t *testing.T) { - assert := New(new(testing.T)) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } -} - -func TestRegexpWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, assert.Regexp(tc.rx, tc.str)) - True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - False(t, assert.NotRegexp(tc.rx, tc.str)) - False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - True(t, assert.NotRegexp(tc.rx, tc.str)) - True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index 0419c1b6..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,157 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, mode, url string, values url.Values) int { - w := httptest.NewRecorder() - req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) - if err != nil { - return -1 - } - handler(w, req) - return w.Code -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { - code := httpCode(handler, mode, url, values) - if code == -1 { - return false - } - return code >= http.StatusOK && code <= http.StatusPartialContent -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { - code := httpCode(handler, mode, url, values) - if code == -1 { - return false - } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { - code := httpCode(handler, mode, url, values) - if code == -1 { - return false - } - return code >= http.StatusBadRequest -} - -// HttpBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HttpBody(handler http.HandlerFunc, mode, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { - body := HttpBody(handler, mode, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { - body := HttpBody(handler, mode, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) - } - - return !contains -} - -// -// Assertions Wrappers -// - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url string, values url.Values) bool { - return HTTPSuccess(a.t, handler, mode, url, values) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url string, values url.Values) bool { - return HTTPRedirect(a.t, handler, mode, url, values) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url string, values url.Values) bool { - return HTTPError(a.t, handler, mode, url, values) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { - return HTTPBodyContains(a.t, handler, mode, url, values, str) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { - return HTTPBodyNotContains(a.t, handler, mode, url, values, str) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go deleted file mode 100644 index 684c2d5d..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/url" - "testing" -) - -func httpOK(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func httpRedirect(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTemporaryRedirect) -} - -func httpError(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) -} - -func TestHTTPStatuses(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) - assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) - assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) -} - -func TestHTTPStatusesWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) -} - -func httpHelloName(w http.ResponseWriter, r *http.Request) { - name := r.FormValue("name") - w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) -} - -func TestHttpBody(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) -} - -func TestHttpBodyWrappers(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/doc.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/doc.go deleted file mode 100644 index dd385074..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/doc.go +++ /dev/null @@ -1,43 +0,0 @@ -// Provides a system by which it is possible to mock your objects and verify calls are happening as expected. -// -// Example Usage -// -// The mock package provides an object, Mock, that tracks activity on another object. It is usually -// embedded into a test object as shown below: -// -// type MyTestObject struct { -// // add a Mock object instance -// mock.Mock -// -// // other fields go here as normal -// } -// -// When implementing the methods of an interface, you wire your functions up -// to call the Mock.Called(args...) method, and return the appropriate values. -// -// For example, to mock a method that saves the name and age of a person and returns -// the year of their birth or an error, you might write this: -// -// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { -// args := o.Called(firstname, lastname, age) -// return args.Int(0), args.Error(1) -// } -// -// The Int, Error and Bool methods are examples of strongly typed getters that take the argument -// index position. Given this argument list: -// -// (12, true, "Something") -// -// You could read them out strongly typed like this: -// -// args.Int(0) -// args.Bool(1) -// args.String(2) -// -// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: -// -// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) -// -// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those -// cases you should check for nil first. -package mock diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go deleted file mode 100644 index f73fa251..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock.go +++ /dev/null @@ -1,510 +0,0 @@ -package mock - -import ( - "fmt" - "github.com/stretchr/objx" - "github.com/stretchr/testify/assert" - "reflect" - "runtime" - "strings" - "sync" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Logf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) -} - -/* - Call -*/ - -// Call represents a method call and is used for setting expectations, -// as well as recording activity. -type Call struct { - - // The name of the method that was or will be called. - Method string - - // Holds the arguments of the method. - Arguments Arguments - - // Holds the arguments that should be returned when - // this method is called. - ReturnArguments Arguments - - // The number of times to return the return arguments when setting - // expectations. 0 means to always return the value. - Repeatability int -} - -// Mock is the workhorse used to track activity on another object. -// For an example of its usage, refer to the "Example Usage" section at the top of this document. -type Mock struct { - - // The method name that is currently - // being referred to by the On method. - onMethodName string - - // An array of the arguments that are - // currently being referred to by the On method. - onMethodArguments Arguments - - // Represents the calls that are expected of - // an object. - ExpectedCalls []Call - - // Holds the calls that were made to this mocked object. - Calls []Call - - // TestData holds any data that might be useful for testing. Testify ignores - // this data completely allowing you to do whatever you like with it. - testData objx.Map - - mutex sync.Mutex -} - -// TestData holds any data that might be useful for testing. Testify ignores -// this data completely allowing you to do whatever you like with it. -func (m *Mock) TestData() objx.Map { - - if m.testData == nil { - m.testData = make(objx.Map) - } - - return m.testData -} - -/* - Setting expectations -*/ - -// On starts a description of an expectation of the specified method -// being called. -// -// Mock.On("MyMethod", arg1, arg2) -func (m *Mock) On(methodName string, arguments ...interface{}) *Mock { - m.onMethodName = methodName - m.onMethodArguments = arguments - return m -} - -// Return finishes a description of an expectation of the method (and arguments) -// specified in the most recent On method call. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2) -func (m *Mock) Return(returnArguments ...interface{}) *Mock { - m.ExpectedCalls = append(m.ExpectedCalls, Call{m.onMethodName, m.onMethodArguments, returnArguments, 0}) - return m -} - -// Once indicates that that the mock should only return the value once. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() -func (m *Mock) Once() { - m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 1 -} - -// Twice indicates that that the mock should only return the value twice. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() -func (m *Mock) Twice() { - m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = 2 -} - -// Times indicates that that the mock should only return the indicated number -// of times. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) -func (m *Mock) Times(i int) { - m.ExpectedCalls[len(m.ExpectedCalls)-1].Repeatability = i -} - -/* - Recording and responding to activity -*/ - -func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { - for i, call := range m.ExpectedCalls { - if call.Method == method && call.Repeatability > -1 { - - _, diffCount := call.Arguments.Diff(arguments) - if diffCount == 0 { - return i, &call - } - - } - } - return -1, nil -} - -func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) { - - diffCount := 0 - var closestCall *Call = nil - - for _, call := range m.ExpectedCalls { - if call.Method == method { - - _, tempDiffCount := call.Arguments.Diff(arguments) - if tempDiffCount < diffCount || diffCount == 0 { - diffCount = tempDiffCount - closestCall = &call - } - - } - } - - if closestCall == nil { - return false, nil - } - - return true, closestCall -} - -func callString(method string, arguments Arguments, includeArgumentValues bool) string { - - var argValsString string = "" - if includeArgumentValues { - var argVals []string - for argIndex, arg := range arguments { - argVals = append(argVals, fmt.Sprintf("%d: %v", argIndex, arg)) - } - argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) - } - - return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) -} - -// Called tells the mock object that a method has been called, and gets an array -// of arguments to return. Panics if the call is unexpected (i.e. not preceeded by -// appropriate .On .Return() calls) -func (m *Mock) Called(arguments ...interface{}) Arguments { - defer m.mutex.Unlock() - m.mutex.Lock() - - // get the calling function's name - pc, _, _, ok := runtime.Caller(1) - if !ok { - panic("Couldn't get the caller information") - } - functionPath := runtime.FuncForPC(pc).Name() - parts := strings.Split(functionPath, ".") - functionName := parts[len(parts)-1] - - found, call := m.findExpectedCall(functionName, arguments...) - - switch { - case found < 0: - // we have to fail here - because we don't know what to do - // as the return arguments. This is because: - // - // a) this is a totally unexpected call to this method, - // b) the arguments are not what was expected, or - // c) the developer has forgotten to add an accompanying On...Return pair. - - closestFound, closestCall := m.findClosestCall(functionName, arguments...) - - if closestFound { - panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n", callString(functionName, arguments, true), callString(functionName, closestCall.Arguments, true))) - } else { - panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", functionName, functionName, callString(functionName, arguments, true), assert.CallerInfo())) - } - case call.Repeatability == 1: - call.Repeatability = -1 - m.ExpectedCalls[found] = *call - case call.Repeatability > 1: - call.Repeatability -= 1 - m.ExpectedCalls[found] = *call - } - - // add the call - m.Calls = append(m.Calls, Call{functionName, arguments, make([]interface{}, 0), 0}) - - return call.ReturnArguments - -} - -/* - Assertions -*/ - -// AssertExpectationsForObjects asserts that everything specified with On and Return -// of the specified objects was in fact called as expected. -// -// Calls may have occurred in any order. -func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { - var success bool = true - for _, obj := range testObjects { - mockObj := obj.(Mock) - success = success && mockObj.AssertExpectations(t) - } - return success -} - -// AssertExpectations asserts that everything specified with On and Return was -// in fact called as expected. Calls may have occurred in any order. -func (m *Mock) AssertExpectations(t TestingT) bool { - - var somethingMissing bool = false - var failedExpectations int = 0 - - // iterate through each expectation - for _, expectedCall := range m.ExpectedCalls { - switch { - case !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments): - somethingMissing = true - failedExpectations++ - t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) - case expectedCall.Repeatability > 0: - somethingMissing = true - failedExpectations++ - default: - t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) - } - } - - if somethingMissing { - t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(m.ExpectedCalls)-failedExpectations, len(m.ExpectedCalls), failedExpectations, assert.CallerInfo()) - } - - return !somethingMissing -} - -// AssertNumberOfCalls asserts that the method was called expectedCalls times. -func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { - var actualCalls int = 0 - for _, call := range m.Calls { - if call.Method == methodName { - actualCalls++ - } - } - return assert.Equal(t, actualCalls, expectedCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) -} - -// AssertCalled asserts that the method was called. -func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) { - t.Logf("%s", m.ExpectedCalls) - return false - } - return true -} - -// AssertNotCalled asserts that the method was not called. -func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) { - t.Logf("%s", m.ExpectedCalls) - return false - } - return true -} - -func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { - for _, call := range m.Calls { - if call.Method == methodName { - - _, differences := Arguments(expected).Diff(call.Arguments) - - if differences == 0 { - // found the expected call - return true - } - - } - } - // we didn't find the expected call - return false -} - -/* - Arguments -*/ - -// Arguments holds an array of method arguments or return values. -type Arguments []interface{} - -const ( - // The "any" argument. Used in Diff and Assert when - // the argument being tested shouldn't be taken into consideration. - Anything string = "mock.Anything" -) - -// AnythingOfTypeArgument is a string that contains the type of an argument -// for use when type checking. Used in Diff and Assert. -type AnythingOfTypeArgument string - -// AnythingOfType returns an AnythingOfTypeArgument object containing the -// name of the type to check for. Used in Diff and Assert. -// -// For example: -// Assert(t, AnythingOfType("string"), AnythingOfType("int")) -func AnythingOfType(t string) AnythingOfTypeArgument { - return AnythingOfTypeArgument(t) -} - -// Get Returns the argument at the specified index. -func (args Arguments) Get(index int) interface{} { - if index+1 > len(args) { - panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) - } - return args[index] -} - -// Is gets whether the objects match the arguments specified. -func (args Arguments) Is(objects ...interface{}) bool { - for i, obj := range args { - if obj != objects[i] { - return false - } - } - return true -} - -// Diff gets a string describing the differences between the arguments -// and the specified objects. -// -// Returns the diff string and number of differences found. -func (args Arguments) Diff(objects []interface{}) (string, int) { - - var output string = "\n" - var differences int - - var maxArgCount int = len(args) - if len(objects) > maxArgCount { - maxArgCount = len(objects) - } - - for i := 0; i < maxArgCount; i++ { - var actual, expected interface{} - - if len(objects) <= i { - actual = "(Missing)" - } else { - actual = objects[i] - } - - if len(args) <= i { - expected = "(Missing)" - } else { - expected = args[i] - } - - if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { - - // type checking - if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: \u274C type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) - } - - } else { - - // normal checking - - if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { - // match - output = fmt.Sprintf("%s\t%d: \u2705 %s == %s\n", output, i, actual, expected) - } else { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: \u274C %s != %s\n", output, i, actual, expected) - } - } - - } - - if differences == 0 { - return "No differences.", differences - } - - return output, differences - -} - -// Assert compares the arguments with the specified objects and fails if -// they do not exactly match. -func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { - - // get the differences - diff, diffCount := args.Diff(objects) - - if diffCount == 0 { - return true - } - - // there are differences... report them... - t.Logf(diff) - t.Errorf("%sArguments do not match.", assert.CallerInfo()) - - return false - -} - -// String gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -// -// If no index is provided, String() returns a complete string representation -// of the arguments. -func (args Arguments) String(indexOrNil ...int) string { - - if len(indexOrNil) == 0 { - // normal String() method - return a string representation of the args - var argsStr []string - for _, arg := range args { - argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) - } - return strings.Join(argsStr, ",") - } else if len(indexOrNil) == 1 { - // Index has been specified - get the argument at that index - var index int = indexOrNil[0] - var s string - var ok bool - if s, ok = args.Get(index).(string); !ok { - panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) - } - return s - } - - panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) - -} - -// Int gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Int(index int) int { - var s int - var ok bool - if s, ok = args.Get(index).(int); !ok { - panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Error gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Error(index int) error { - obj := args.Get(index) - var s error - var ok bool - if obj == nil { - return nil - } - if s, ok = obj.(error); !ok { - panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Bool gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Bool(index int) bool { - var s bool - var ok bool - if s, ok = args.Get(index).(bool); !ok { - panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go deleted file mode 100644 index a4457e07..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go +++ /dev/null @@ -1,669 +0,0 @@ -package mock - -import ( - "errors" - "github.com/stretchr/testify/assert" - "testing" -) - -/* - Test objects -*/ - -// ExampleInterface represents an example interface. -type ExampleInterface interface { - TheExampleMethod(a, b, c int) (int, error) -} - -// TestExampleImplementation is a test implementation of ExampleInterface -type TestExampleImplementation struct { - Mock -} - -func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { - args := i.Called(a, b, c) - return args.Int(0), errors.New("Whoops") -} - -func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { - i.Called(yesorno) -} - -type ExampleType struct{} - -func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { - args := i.Called(et) - return args.Error(0) -} - -/* - Mock -*/ - -func Test_Mock_TestData(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - if assert.NotNil(t, mockedService.TestData()) { - - mockedService.TestData().Set("something", 123) - assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) - - } - -} - -func Test_Mock_On(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod"), &mockedService.Mock) - assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) - -} - -func Test_Mock_On_WithArgs(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", 1, 2, 3), &mockedService.Mock) - assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) - assert.Equal(t, 1, mockedService.onMethodArguments[0]) - assert.Equal(t, 2, mockedService.onMethodArguments[1]) - assert.Equal(t, 3, mockedService.onMethodArguments[2]) - -} - -func Test_Mock_Return(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - - } - -} - -func Test_Mock_Return_Once(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Once() - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 1, call.Repeatability) - - } - -} - -func Test_Mock_Return_Twice(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Twice() - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 2, call.Repeatability) - - } - -} - -func Test_Mock_Return_Times(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Times(5) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 5, call.Repeatability) - - } - -} - -func Test_Mock_Return_Nothing(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 0, len(call.ReturnArguments)) - - } - -} - -func Test_Mock_findExpectedCall(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, _ := m.findExpectedCall("Two") - - assert.Equal(t, -1, f) - -} - -func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two").Once() - m.On("Two", 3).Return("three").Twice() - m.On("Two", 3).Return("three").Times(8) - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_callString(t *testing.T) { - - assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) - -} - -func Test_Mock_Called(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) - - returnArguments := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 1, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments)) { - assert.Equal(t, 5, returnArguments[0]) - assert.Equal(t, "6", returnArguments[1]) - assert.Equal(t, true, returnArguments[2]) - } - -} - -func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(5, "6", true).Once() - mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(-1, "hi", false) - - returnArguments1 := mockedService.Called(1, 2, 3) - returnArguments2 := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 2, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) - assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments1)) { - assert.Equal(t, 5, returnArguments1[0]) - assert.Equal(t, "6", returnArguments1[1]) - assert.Equal(t, true, returnArguments1[2]) - } - - if assert.Equal(t, 3, len(returnArguments2)) { - assert.Equal(t, -1, returnArguments2[0]) - assert.Equal(t, "hi", returnArguments2[1]) - assert.Equal(t, false, returnArguments2[2]) - } - -} - -func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) - - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - assert.Panics(t, func() { - mockedService.TheExampleMethod(1, 2, 3) - }) - -} - -func Test_Mock_Called_Unexpected(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - // make sure it panics if no expectation was made - assert.Panics(t, func() { - mockedService.Called(1, 2, 3) - }, "Calling unexpected method should panic") - -} - -func Test_AssertExpectationsForObjects_Helper(t *testing.T) { - - var mockedService1 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService2 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService3 *TestExampleImplementation = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() - - mockedService1.Called(1) - mockedService2.Called(2) - mockedService3.Called(3) - - assert.True(t, AssertExpectationsForObjects(t, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) - -} - -func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { - - var mockedService1 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService2 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService3 *TestExampleImplementation = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() - - mockedService1.Called(1) - mockedService3.Called(3) - - tt := new(testing.T) - assert.False(t, AssertExpectationsForObjects(tt, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) - -} - -func Test_Mock_AssertExpectations(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectationsCustomType(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.TheExampleMethod3(&ExampleType{}) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - assert.False(t, mockedService.AssertExpectations(tt)) - - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) - - args1 := mockedService.Called(1, 2, 3) - assert.Equal(t, 5, args1.Int(0)) - assert.Equal(t, 6, args1.Int(1)) - assert.Equal(t, 7, args1.Int(2)) - - args2 := mockedService.Called(4, 5, 6) - assert.Equal(t, 5, args2.Int(0)) - assert.Equal(t, 6, args2.Int(1)) - assert.Equal(t, 7, args2.Int(2)) - -} - -func Test_Mock_AssertNumberOfCalls(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) - -} - -func Test_Mock_AssertCalled(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) - -} - -func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).Return() - - mockedService.Called(1, "two", []uint8("three")) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) - -} - -func Test_Mock_AssertCalled_WithArguments(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) - -} - -func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() - - mockedService.Called(1, 2, 3) - mockedService.Called(2, 3, 4) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) - -} - -func Test_Mock_AssertNotCalled(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) - -} - -/* - Arguments helper methods -*/ -func Test_Arguments_Get(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.Equal(t, "string", args.Get(0).(string)) - assert.Equal(t, 123, args.Get(1).(int)) - assert.Equal(t, true, args.Get(2).(bool)) - -} - -func Test_Arguments_Is(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.True(t, args.Is("string", 123, true)) - assert.False(t, args.Is("wrong", 456, false)) - -} - -func Test_Arguments_Diff(t *testing.T) { - - var args Arguments = []interface{}{"Hello World", 123, true} - var diff string - var count int - diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) - - assert.Equal(t, 2, count) - assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) - assert.Contains(t, diff, `false != %!s(bool=true)`) - -} - -func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - var diff string - var count int - diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) - - assert.Equal(t, 3, count) - assert.Contains(t, diff, `extra != (Missing)`) - -} - -func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - var count int - _, count = args.Diff([]interface{}{"string", Anything, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { - - var args Arguments = []interface{}{"string", Anything, true} - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { - - var args Arguments = []interface{}{"string", AnythingOfType("int"), true} - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { - - var args Arguments = []interface{}{"string", AnythingOfType("string"), true} - var count int - var diff string - diff, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 1, count) - assert.Contains(t, diff, `string != type int - %!s(int=123)`) - -} - -func Test_Arguments_Assert(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.True(t, args.Assert(t, "string", 123, true)) - -} - -func Test_Arguments_String_Representation(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, `string,int,bool`, args.String()) - -} - -func Test_Arguments_String(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, "string", args.String(0)) - -} - -func Test_Arguments_Error(t *testing.T) { - - var err error = errors.New("An Error") - var args Arguments = []interface{}{"string", 123, true, err} - assert.Equal(t, err, args.Error(3)) - -} - -func Test_Arguments_Error_Nil(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true, nil} - assert.Equal(t, nil, args.Error(3)) - -} - -func Test_Arguments_Int(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, 123, args.Int(1)) - -} - -func Test_Arguments_Bool(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, true, args.Bool(2)) - -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/LICENSE b/Godeps/_workspace/src/github.com/vaughan0/go-ini/LICENSE deleted file mode 100644 index 968b4538..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/LICENSE +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2013 Vaughan Newton - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the -Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/README.md b/Godeps/_workspace/src/github.com/vaughan0/go-ini/README.md deleted file mode 100644 index d5cd4e74..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/README.md +++ /dev/null @@ -1,70 +0,0 @@ -go-ini -====== - -INI parsing library for Go (golang). - -View the API documentation [here](http://godoc.org/github.com/vaughan0/go-ini). - -Usage ------ - -Parse an INI file: - -```go -import "github.com/vaughan0/go-ini" - -file, err := ini.LoadFile("myfile.ini") -``` - -Get data from the parsed file: - -```go -name, ok := file.Get("person", "name") -if !ok { - panic("'name' variable missing from 'person' section") -} -``` - -Iterate through values in a section: - -```go -for key, value := range file["mysection"] { - fmt.Printf("%s => %s\n", key, value) -} -``` - -Iterate through sections in a file: - -```go -for name, section := range file { - fmt.Printf("Section name: %s\n", name) -} -``` - -File Format ------------ - -INI files are parsed by go-ini line-by-line. Each line may be one of the following: - - * A section definition: [section-name] - * A property: key = value - * A comment: #blahblah _or_ ;blahblah - * Blank. The line will be ignored. - -Properties defined before any section headers are placed in the default section, which has -the empty string as it's key. - -Example: - -```ini -# I am a comment -; So am I! - -[apples] -colour = red or green -shape = applish - -[oranges] -shape = square -colour = blue -``` diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini.go b/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini.go deleted file mode 100644 index 81aeb32f..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini.go +++ /dev/null @@ -1,123 +0,0 @@ -// Package ini provides functions for parsing INI configuration files. -package ini - -import ( - "bufio" - "fmt" - "io" - "os" - "regexp" - "strings" -) - -var ( - sectionRegex = regexp.MustCompile(`^\[(.*)\]$`) - assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`) -) - -// ErrSyntax is returned when there is a syntax error in an INI file. -type ErrSyntax struct { - Line int - Source string // The contents of the erroneous line, without leading or trailing whitespace -} - -func (e ErrSyntax) Error() string { - return fmt.Sprintf("invalid INI syntax on line %d: %s", e.Line, e.Source) -} - -// A File represents a parsed INI file. -type File map[string]Section - -// A Section represents a single section of an INI file. -type Section map[string]string - -// Returns a named Section. A Section will be created if one does not already exist for the given name. -func (f File) Section(name string) Section { - section := f[name] - if section == nil { - section = make(Section) - f[name] = section - } - return section -} - -// Looks up a value for a key in a section and returns that value, along with a boolean result similar to a map lookup. -func (f File) Get(section, key string) (value string, ok bool) { - if s := f[section]; s != nil { - value, ok = s[key] - } - return -} - -// Loads INI data from a reader and stores the data in the File. -func (f File) Load(in io.Reader) (err error) { - bufin, ok := in.(*bufio.Reader) - if !ok { - bufin = bufio.NewReader(in) - } - return parseFile(bufin, f) -} - -// Loads INI data from a named file and stores the data in the File. -func (f File) LoadFile(file string) (err error) { - in, err := os.Open(file) - if err != nil { - return - } - defer in.Close() - return f.Load(in) -} - -func parseFile(in *bufio.Reader, file File) (err error) { - section := "" - lineNum := 0 - for done := false; !done; { - var line string - if line, err = in.ReadString('\n'); err != nil { - if err == io.EOF { - done = true - } else { - return - } - } - lineNum++ - line = strings.TrimSpace(line) - if len(line) == 0 { - // Skip blank lines - continue - } - if line[0] == ';' || line[0] == '#' { - // Skip comments - continue - } - - if groups := assignRegex.FindStringSubmatch(line); groups != nil { - key, val := groups[1], groups[2] - key, val = strings.TrimSpace(key), strings.TrimSpace(val) - file.Section(section)[key] = val - } else if groups := sectionRegex.FindStringSubmatch(line); groups != nil { - name := strings.TrimSpace(groups[1]) - section = name - // Create the section if it does not exist - file.Section(section) - } else { - return ErrSyntax{lineNum, line} - } - - } - return nil -} - -// Loads and returns a File from a reader. -func Load(in io.Reader) (File, error) { - file := make(File) - err := file.Load(in) - return file, err -} - -// Loads and returns an INI File from a file on disk. -func LoadFile(filename string) (File, error) { - file := make(File) - err := file.LoadFile(filename) - return file, err -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go b/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go deleted file mode 100644 index 38a6f000..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_linux_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package ini - -import ( - "reflect" - "syscall" - "testing" -) - -func TestLoadFile(t *testing.T) { - originalOpenFiles := numFilesOpen(t) - - file, err := LoadFile("test.ini") - if err != nil { - t.Fatal(err) - } - - if originalOpenFiles != numFilesOpen(t) { - t.Error("test.ini not closed") - } - - if !reflect.DeepEqual(file, File{"default": {"stuff": "things"}}) { - t.Error("file not read correctly") - } -} - -func numFilesOpen(t *testing.T) (num uint64) { - var rlimit syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatal(err) - } - maxFds := int(rlimit.Cur) - - var stat syscall.Stat_t - for i := 0; i < maxFds; i++ { - if syscall.Fstat(i, &stat) == nil { - num++ - } else { - return - } - } - return -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go b/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go deleted file mode 100644 index 06a4d05e..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/ini_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package ini - -import ( - "reflect" - "strings" - "testing" -) - -func TestLoad(t *testing.T) { - src := ` - # Comments are ignored - - herp = derp - - [foo] - hello=world - whitespace should = not matter - ; sneaky semicolon-style comment - multiple = equals = signs - - [bar] - this = that` - - file, err := Load(strings.NewReader(src)) - if err != nil { - t.Fatal(err) - } - check := func(section, key, expect string) { - if value, _ := file.Get(section, key); value != expect { - t.Errorf("Get(%q, %q): expected %q, got %q", section, key, expect, value) - } - } - - check("", "herp", "derp") - check("foo", "hello", "world") - check("foo", "whitespace should", "not matter") - check("foo", "multiple", "equals = signs") - check("bar", "this", "that") -} - -func TestSyntaxError(t *testing.T) { - src := ` - # Line 2 - [foo] - bar = baz - # Here's an error on line 6: - wut? - herp = derp` - _, err := Load(strings.NewReader(src)) - t.Logf("%T: %v", err, err) - if err == nil { - t.Fatal("expected an error, got nil") - } - syntaxErr, ok := err.(ErrSyntax) - if !ok { - t.Fatal("expected an error of type ErrSyntax") - } - if syntaxErr.Line != 6 { - t.Fatal("incorrect line number") - } - if syntaxErr.Source != "wut?" { - t.Fatal("incorrect source") - } -} - -func TestDefinedSectionBehaviour(t *testing.T) { - check := func(src string, expect File) { - file, err := Load(strings.NewReader(src)) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(file, expect) { - t.Errorf("expected %v, got %v", expect, file) - } - } - // No sections for an empty file - check("", File{}) - // Default section only if there are actually values for it - check("foo=bar", File{"": {"foo": "bar"}}) - // User-defined sections should always be present, even if empty - check("[a]\n[b]\nfoo=bar", File{ - "a": {}, - "b": {"foo": "bar"}, - }) - check("foo=bar\n[a]\nthis=that", File{ - "": {"foo": "bar"}, - "a": {"this": "that"}, - }) -} diff --git a/Godeps/_workspace/src/github.com/vaughan0/go-ini/test.ini b/Godeps/_workspace/src/github.com/vaughan0/go-ini/test.ini deleted file mode 100644 index d13c999e..00000000 --- a/Godeps/_workspace/src/github.com/vaughan0/go-ini/test.ini +++ /dev/null @@ -1,2 +0,0 @@ -[default] -stuff = things diff --git a/Makefile b/Makefile index 265f67ca..21692f04 100644 --- a/Makefile +++ b/Makefile @@ -65,3 +65,4 @@ install: test-all clean: @rm -fv cover.out + @rm -fv mc diff --git a/cmd-access.go b/cmd-access.go index 49b97223..75b7afb9 100644 --- a/cmd-access.go +++ b/cmd-access.go @@ -24,7 +24,6 @@ import ( "github.com/minio-io/mc/pkg/client" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) func runAccessCmd(ctx *cli.Context) { @@ -36,7 +35,7 @@ func runAccessCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("loading config file failed with following reason: [%s]\n", iodine.ToError(err)) } targetURLConfigMap := make(map[string]*hostConfig) @@ -44,44 +43,44 @@ func runAccessCmd(ctx *cli.Context) { if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("reading URL [%s] failed with following reason: [%s]\n", e.url, e) default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("reading URLs failed with following reason: [%s]\n", e) } } acl := bucketACL(ctx.Args().First()) if !acl.isValidBucketACL() { - log.Debug.Println(iodine.New(errInvalidACL{acl: acl.String()}, nil)) + console.Debugln(iodine.New(errInvalidACL{acl: acl.String()}, nil)) console.Fatalf("Access type [%s] is not supported. Valid types are [private, public, readonly].\n", acl) } targetURLs = targetURLs[1:] // 1 or more target URLs for _, targetURL := range targetURLs { targetConfig, err := getHostConfig(targetURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read configuration for host [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) } targetURLConfigMap[targetURL] = targetConfig } for targetURL, targetConfig := range targetURLConfigMap { - errorMsg, err := doUpdateAccessCmd(mcClientMethods{}, targetURL, acl.String(), targetConfig, globalDebugFlag) + errorMsg, err := doUpdateAccessCmd(targetURL, acl.String(), targetConfig, globalDebugFlag) err = iodine.New(err, nil) if err != nil { if errorMsg == "" { errorMsg = "Empty error message. Please rerun this command with --debug and file a bug report." } - log.Debug.Println(err) + console.Debugln(err) console.Errorf("%s", errorMsg) } } } -func doUpdateAccessCmd(methods clientMethods, targetURL, targetACL string, targetConfig *hostConfig, debug bool) (string, error) { +func doUpdateAccessCmd(targetURL, targetACL string, targetConfig *hostConfig, debug bool) (string, error) { var err error var clnt client.Client - clnt, err = methods.getNewClient(targetURL, targetConfig, debug) + clnt, err = getNewClient(targetURL, targetConfig, debug) if err != nil { err := iodine.New(err, nil) msg := fmt.Sprintf("Unable to initialize client for [%s]. Reason: [%s].\n", diff --git a/cmd-cat.go b/cmd-cat.go index 3aaf151b..a19cbf5c 100644 --- a/cmd-cat.go +++ b/cmd-cat.go @@ -26,7 +26,6 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) func runCatCmd(ctx *cli.Context) { @@ -38,7 +37,7 @@ func runCatCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("loading config file failed with following reason: [%s]\n", iodine.ToError(err)) } @@ -47,10 +46,10 @@ func runCatCmd(ctx *cli.Context) { if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("reading URL [%s] failed with following reason: [%s]\n", e.url, e) default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("reading URLs failed with following reason: [%s]\n", e) } } @@ -58,19 +57,19 @@ func runCatCmd(ctx *cli.Context) { sourceURLs := urls sourceURLConfigMap, err := getHostConfigs(sourceURLs) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("reading host config for URL [%s] failed with following reason: [%s]\n", sourceURLs, iodine.ToError(err)) } - humanReadable, err := doCatCmd(mcClientMethods{}, sourceURLConfigMap, globalDebugFlag) + humanReadable, err := doCatCmd(sourceURLConfigMap, globalDebugFlag) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalln(humanReadable) } } -func doCatCmd(methods clientMethods, sourceURLConfigMap map[string]*hostConfig, debug bool) (string, error) { +func doCatCmd(sourceURLConfigMap map[string]*hostConfig, debug bool) (string, error) { for url, config := range sourceURLConfigMap { - sourceClnt, err := methods.getNewClient(url, config, debug) + sourceClnt, err := getNewClient(url, config, debug) if err != nil { return "Unable to create client: " + url, iodine.New(err, nil) } diff --git a/cmd-config.go b/cmd-config.go index c94945a9..33b548d7 100644 --- a/cmd-config.go +++ b/cmd-config.go @@ -23,7 +23,6 @@ import ( "github.com/minio-io/mc/pkg/console" "github.com/minio-io/mc/pkg/quick" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) // runConfigCmd is the handle for "mc config" sub-command @@ -35,12 +34,12 @@ func runConfigCmd(ctx *cli.Context) { arg := ctx.Args().First() tailArgs := ctx.Args().Tail() if len(tailArgs) > 2 { - log.Debug.Println(iodine.New(errInvalidArgument{}, nil)) + console.Debugln(iodine.New(errInvalidArgument{}, nil)) console.Fatalln("Incorrect number of arguments, please use \"mc config help\"") } msg, err := doConfig(arg, tailArgs) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalln(msg) } console.Infoln(msg) diff --git a/cmd-cp.go b/cmd-cp.go index ec6f91a6..65a14189 100644 --- a/cmd-cp.go +++ b/cmd-cp.go @@ -22,7 +22,6 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) func runCopyCmd(ctx *cli.Context) { @@ -34,7 +33,7 @@ func runCopyCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) } @@ -43,29 +42,28 @@ func runCopyCmd(ctx *cli.Context) { if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unknown type of URL(s).\n") default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to parse arguments. Reason: [%s].\n", e) } } - methods := mcClientMethods{} switch len(urls) { case 2: - runCopyCmdSingleSource(methods, urls) + runCopyCmdSingleSource(urls) default: - runCopyCmdMultipleSources(methods, urls) + runCopyCmdMultipleSources(urls) } } -func runCopyCmdMultipleSources(methods clientMethods, urls []string) { +func runCopyCmdMultipleSources(urls []string) { sourceURLs := urls[:len(urls)-1] // All args are source except the last one targetURL := urls[len(urls)-1] // Last one is target targetConfig, err := getHostConfig(targetURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the following targets %s from config file [%s]. Reason: [%s].\n", targetURL, mustGetMcConfigPath(), iodine.ToError(err)) } @@ -84,38 +82,38 @@ func runCopyCmdMultipleSources(methods clientMethods, urls []string) { for _, newRecursiveSourceURL := range newRecursiveSourceURLs { newRecursiveSourceConfig, err := getHostConfig(newRecursiveSourceURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the source %s from config file [%s]. Reason: [%s].\n", newRecursiveSourceURL, mustGetMcConfigPath(), iodine.ToError(err)) } - err = doCopySingleSourceRecursive(methods, newRecursiveSourceURL, targetURL, newRecursiveSourceConfig, targetConfig) + err = doCopySingleSourceRecursive(newRecursiveSourceURL, targetURL, newRecursiveSourceConfig, targetConfig) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to copy from source %s to target %s. Reason: [%s].\n", newRecursiveSourceURL, targetURL, iodine.ToError(err)) } } newRegularSourceURLConfigMap, err := getHostConfigs(newRegularSourceURLs) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the following sources [%s] from config file [%s]. Reason: [%s].\n", newRegularSourceURLs, mustGetMcConfigPath(), iodine.ToError(err)) } - err = doCopyMultipleSources(methods, newRegularSourceURLConfigMap, targetURL, targetConfig) + err = doCopyMultipleSources(newRegularSourceURLConfigMap, targetURL, targetConfig) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to copy from following sources [%s] to target %s. Reason: [%s].\n", newRegularSourceURLs, targetURL, iodine.ToError(err)) } } -func runCopyCmdSingleSource(methods clientMethods, urls []string) { +func runCopyCmdSingleSource(urls []string) { sourceURL := urls[0] targetURL := urls[1] targetConfig, err := getHostConfig(targetURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the following targets %s from config file [%s]. Reason: [%s].\n", targetURL, mustGetMcConfigPath(), iodine.ToError(err)) } @@ -126,21 +124,21 @@ func runCopyCmdSingleSource(methods clientMethods, urls []string) { } sourceConfig, err := getHostConfig(sourceURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the following targets %s from config file [%s]. Reason: [%s].\n", sourceURL, mustGetMcConfigPath(), iodine.ToError(err)) } if recursive { - err = doCopySingleSourceRecursive(methods, sourceURL, targetURL, sourceConfig, targetConfig) + err = doCopySingleSourceRecursive(sourceURL, targetURL, sourceConfig, targetConfig) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to copy from source [%s] to target %s. Reason: [%s].\n", sourceURL, targetURL, iodine.ToError(err)) } return } - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) + err = doCopySingleSource(sourceURL, targetURL, sourceConfig, targetConfig) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to copy from source [%s] to target %s. Reason: [%s].\n", sourceURL, targetURL, iodine.ToError(err)) } diff --git a/cmd-ls.go b/cmd-ls.go index 4944d0a4..2286c4a3 100644 --- a/cmd-ls.go +++ b/cmd-ls.go @@ -24,7 +24,6 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) // runListCmd - is a handler for mc ls command @@ -37,7 +36,7 @@ func runListCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) } targetURLConfigMap := make(map[string]*hostConfig) @@ -46,16 +45,16 @@ func runListCmd(ctx *cli.Context) { if err != nil { switch iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unknown type of URL [%s].\n", arg) default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to parse argument [%s]. Reason: [%s].\n", arg, iodine.ToError(err)) } } targetConfig, err := getHostConfig(targetURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for [%s] from config file [%s]. Reason: [%s].\n", targetURL, mustGetMcConfigPath(), iodine.ToError(err)) } @@ -65,17 +64,17 @@ func runListCmd(ctx *cli.Context) { if isURLRecursive(targetURL) { // if recursive strip off the "..." targetURL = strings.TrimSuffix(targetURL, recursiveSeparator) - err = doListRecursiveCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) + err = doListRecursiveCmd(targetURL, targetConfig, globalDebugFlag) err = iodine.New(err, nil) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to list [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) } } else { - err = doListCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) + err = doListCmd(targetURL, targetConfig, globalDebugFlag) if err != nil { if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to list [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) } } @@ -84,8 +83,8 @@ func runListCmd(ctx *cli.Context) { } // doListCmd - -func doListCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) error { - clnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) +func doListCmd(targetURL string, targetConfig *hostConfig, debug bool) error { + clnt, err := getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { return iodine.New(err, map[string]string{"Target": targetURL}) } @@ -103,8 +102,8 @@ func doListCmd(methods clientMethods, targetURL string, targetConfig *hostConfig } // doListRecursiveCmd - -func doListRecursiveCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) error { - clnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) +func doListRecursiveCmd(targetURL string, targetConfig *hostConfig, debug bool) error { + clnt, err := getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { return iodine.New(err, map[string]string{"Target": targetURL}) } diff --git a/cmd-mb.go b/cmd-mb.go index d5253c41..3fa82b00 100644 --- a/cmd-mb.go +++ b/cmd-mb.go @@ -24,7 +24,6 @@ import ( "github.com/minio-io/mc/pkg/client" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) // runMakeBucketCmd is the handler for mc mb command @@ -37,7 +36,7 @@ func runMakeBucketCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read config file [%s].\n", mustGetMcConfigPath()) } targetURLConfigMap := make(map[string]*hostConfig) @@ -45,39 +44,39 @@ func runMakeBucketCmd(ctx *cli.Context) { if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unknown URL type [%s] passed. Reason: [%s].\n", e.url, e) default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Error in parsing path or URL. Reason: [%s].\n", e) } } for _, targetURL := range targetURLs { targetConfig, err := getHostConfig(targetURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read configuration for host [%s]. Reason: [%s].\n", targetURL, iodine.ToError(err)) } targetURLConfigMap[targetURL] = targetConfig } for targetURL, targetConfig := range targetURLConfigMap { - errorMsg, err := doMakeBucketCmd(mcClientMethods{}, targetURL, targetConfig, globalDebugFlag) + errorMsg, err := doMakeBucketCmd(targetURL, targetConfig, globalDebugFlag) err = iodine.New(err, nil) if err != nil { if errorMsg == "" { errorMsg = "Empty error message. Please rerun this command with --debug and file a bug report." } - log.Debug.Println(err) + console.Debugln(err) console.Errorf("%s", errorMsg) } } } // doMakeBucketCmd - -func doMakeBucketCmd(methods clientMethods, targetURL string, targetConfig *hostConfig, debug bool) (string, error) { +func doMakeBucketCmd(targetURL string, targetConfig *hostConfig, debug bool) (string, error) { var err error var clnt client.Client - clnt, err = methods.getNewClient(targetURL, targetConfig, debug) + clnt, err = getNewClient(targetURL, targetConfig, debug) if err != nil { err := iodine.New(err, nil) msg := fmt.Sprintf("Unable to initialize client for [%s]. Reason: [%s].\n", diff --git a/cmd-sync.go b/cmd-sync.go index beca59b8..44e3e6e4 100644 --- a/cmd-sync.go +++ b/cmd-sync.go @@ -22,7 +22,6 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) func runSyncCmd(ctx *cli.Context) { @@ -34,7 +33,7 @@ func runSyncCmd(ctx *cli.Context) { } config, err := getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read config file [%s]. Reason: [%s].\n", mustGetMcConfigPath(), iodine.ToError(err)) } @@ -43,18 +42,17 @@ func runSyncCmd(ctx *cli.Context) { if err != nil { switch e := iodine.ToError(err).(type) { case errUnsupportedScheme: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unknown type of URL(s).\n") default: - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to parse arguments. Reason: [%s].\n", e) } } - methods := mcClientMethods{} - runCopyCmdSingleSourceMultipleTargets(methods, urls) + runCopyCmdSingleSourceMultipleTargets(urls) } -func runCopyCmdSingleSourceMultipleTargets(methods clientMethods, urls []string) { +func runCopyCmdSingleSourceMultipleTargets(urls []string) { sourceURL := urls[0] // first arg is source targetURLs := urls[1:] // all other are targets @@ -65,21 +63,21 @@ func runCopyCmdSingleSourceMultipleTargets(methods clientMethods, urls []string) } sourceConfig, err := getHostConfig(sourceURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the source %s from config file [%s]. Reason: [%s].\n", sourceURL, mustGetMcConfigPath(), iodine.ToError(err)) } targetURLConfigMap, err := getHostConfigs(targetURLs) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read host configuration for the following targets [%s] from config file [%s]. Reason: [%s].\n", targetURLs, mustGetMcConfigPath(), iodine.ToError(err)) } for targetURL, targetConfig := range targetURLConfigMap { - err = doCopySingleSourceRecursive(methods, sourceURL, targetURL, sourceConfig, targetConfig) + err = doCopySingleSourceRecursive(sourceURL, targetURL, sourceConfig, targetConfig) if err != nil { - log.Debug.Println(err) + console.Debugln(err) console.Fatalf("Failed to copy from source [%s] to target %s. Reason: [%s].\n", sourceURL, targetURL, iodine.ToError(err)) } diff --git a/cmd-update.go b/cmd-update.go index 451242c8..4fd3d732 100644 --- a/cmd-update.go +++ b/cmd-update.go @@ -23,15 +23,14 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) const ( mcUpdateURL = "http://dl.minio.io:9000/updates/2015/Apr" + "/mc" + "." + runtime.GOOS + "." + runtime.GOARCH ) -func doUpdateCheck(methods mcClientMethods, config *hostConfig) (string, error) { - clnt, err := methods.getNewClient(mcUpdateURL, config, globalDebugFlag) +func doUpdateCheck(config *hostConfig) (string, error) { + clnt, err := getNewClient(mcUpdateURL, config, globalDebugFlag) if err != nil { return "Unable to create client: " + mcUpdateURL, iodine.New(err, map[string]string{"failedURL": mcUpdateURL}) } @@ -60,14 +59,14 @@ func runUpdateCmd(ctx *cli.Context) { } hostConfig, err := getHostConfig(mcUpdateURL) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read configuration for host [%s]. Reason: [%s].\n", mcUpdateURL, iodine.ToError(err)) } switch ctx.Args().First() { case "check": - msg, err := doUpdateCheck(mcClientMethods{}, hostConfig) + msg, err := doUpdateCheck(hostConfig) if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf(msg) } } diff --git a/cmd_test.go b/cmd_test.go index 8f3a36d4..bbf6f906 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -17,17 +17,11 @@ package main import ( - "bytes" - "crypto/md5" - "encoding/base64" - "encoding/hex" - "io" "io/ioutil" "os" "os/user" "path" "runtime" - "sync" "testing" "time" @@ -36,8 +30,7 @@ import ( "github.com/cheggaaa/pb" . "github.com/minio-io/check" - "github.com/minio-io/mc/pkg/client" - clientMocks "github.com/minio-io/mc/pkg/client/mocks" + "github.com/minio-io/mc/pkg/quick" "github.com/minio-io/minio/pkg/iodine" ) @@ -47,658 +40,75 @@ type CmdTestSuite struct{} var _ = Suite(&CmdTestSuite{}) -func (s *CmdTestSuite) TestCopyToSingleTarget(c *C) { - methods := &MockclientMethods{} - sourceURL, err := getExpandedURL("foo", nil) - c.Assert(err, IsNil) - - data := "Hello World" - md5Sum := md5.Sum([]byte(data)) - hexMd5 := hex.EncodeToString(md5Sum[:]) - dataLength := int64(len(data)) - - targetURL, err := getExpandedURL("bar", nil) - c.Assert(err, IsNil) - - sourceReader, sourceWriter := io.Pipe() - targetReader, targetWriter := io.Pipe() - var resultBuffer bytes.Buffer - wg := &sync.WaitGroup{} - wg.Add(2) - go func() { - io.Copy(sourceWriter, bytes.NewBufferString("Hello World")) - sourceWriter.Close() - wg.Done() - }() - go func() { - io.Copy(&resultBuffer, targetReader) - wg.Done() - }() - - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - - methods.On("getSourceReader", sourceURL, sourceConfig).Return(sourceReader, dataLength, hexMd5, nil).Once() - methods.On("getTargetWriter", targetURL, targetConfig, hexMd5, dataLength).Return(targetWriter, nil).Once() - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) - c.Assert(err, IsNil) - wg.Wait() - c.Assert(err, IsNil) - c.Assert(resultBuffer.String(), DeepEquals, data) - methods.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestCopyRecursive(c *C) { - sourceURL, err := getExpandedURL("http://example.com/bucket1/", nil) - c.Assert(err, IsNil) - - targetURL, err := getExpandedURL("http://example.com/bucket2/", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - wg := &sync.WaitGroup{} - - data1 := "hello world 1" - binarySum1 := md5.Sum([]byte(data1)) - etag1 := base64.StdEncoding.EncodeToString(binarySum1[:]) - dataLen1 := int64(len(data1)) - reader1, writer1 := io.Pipe() - var results1 bytes.Buffer - var err1 error - - wg.Add(1) - go func() { - _, err1 = io.Copy(&results1, reader1) - wg.Done() - }() - - data2 := "hello world 2" - binarySum2 := md5.Sum([]byte(data2)) - etag2 := base64.StdEncoding.EncodeToString(binarySum2[:]) - dataLen2 := int64(len(data2)) - reader2, writer2 := io.Pipe() - var err2 error - var results2 bytes.Buffer - - wg.Add(1) - go func() { - _, err2 = io.Copy(&results2, reader2) - wg.Done() - }() - - contents := []*client.Content{ - {Name: "hello1", Time: time.Now(), Size: dataLen1}, - {Name: "hello2", Time: time.Now(), Size: dataLen2}, - } - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - contentCh := make(chan client.ContentOnChannel) - go func() { - defer close(contentCh) - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - }() - cl1.On("ListRecursive").Return(contentCh).Once() - sourceReader1 := ioutil.NopCloser(bytes.NewBufferString(data1)) - sourceReader2 := ioutil.NopCloser(bytes.NewBufferString(data2)) - methods.On("getSourceReader", sourceURL+"hello1", sourceConfig).Return(sourceReader1, dataLen1, etag1, nil).Once() - methods.On("getTargetWriter", targetURL+"hello1", targetConfig, etag1, dataLen1).Return(writer1, nil).Once() - methods.On("getSourceReader", sourceURL+"hello2", sourceConfig).Return(sourceReader2, dataLen2, etag2, nil).Once() - methods.On("getTargetWriter", targetURL+"hello2", targetConfig, etag2, dataLen2).Return(writer2, nil).Once() - - err = doCopySingleSourceRecursive(methods, sourceURL, targetURL, sourceConfig, targetConfig) - c.Assert(err, IsNil) - - wg.Wait() - c.Assert(err1, IsNil) - c.Assert(results1.String(), Equals, data1) - c.Assert(err2, IsNil) - c.Assert(results2.String(), Equals, data2) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -type failClose struct{} - -func (c *failClose) Write(p []byte) (int, error) { - return len(p), nil -} -func (c *failClose) Close() error { - return errors.New("Expected Close Error") -} - -func (s *CmdTestSuite) TestCopyCmdFailures(c *C) { - methods := &MockclientMethods{} - sourceURL, err := getExpandedURL("foo", nil) - c.Assert(err, IsNil) - - targetURL, err := getExpandedURL("bar", nil) - c.Assert(err, IsNil) - - var nilReadCloser io.ReadCloser - - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - - methods.On("getSourceReader", sourceURL, sourceConfig).Return(nilReadCloser, int64(0), "", errors.New("Expected Error")).Once() - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) - c.Assert(err, Not(IsNil)) - methods.AssertExpectations(c) - - // source fails - wg := &sync.WaitGroup{} - data1 := "hello1" - binarySum1 := md5.Sum([]byte(data1)) - etag1 := base64.StdEncoding.EncodeToString(binarySum1[:]) - dataLen1 := int64(len(data1)) - reader1, writer1 := io.Pipe() - - methods.On("getSourceReader", sourceURL, sourceConfig).Return(reader1, dataLen1, etag1, nil).Once() - methods.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(nil, errors.New("Expected Error")).Once() - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) - writer1.Close() - wg.Wait() - c.Assert(err, Not(IsNil)) - - // target write fails - reader2, writer2 := io.Pipe() - wg.Add(1) - go func() { - io.CopyN(writer2, bytes.NewBufferString("hel"), 3) - writer2.CloseWithError(errors.New("Expected Error")) - wg.Done() - }() - reader3, writer3 := io.Pipe() - var results3 bytes.Buffer - var n3 int64 - var err3 error - wg.Add(1) - go func() { - n3, err3 = io.Copy(&results3, reader3) - wg.Done() - }() - methods.On("getSourceReader", sourceURL, sourceConfig).Return(reader2, dataLen1, etag1, nil).Once() - methods.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(writer3, nil).Once() - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) - wg.Wait() - c.Assert(err, Not(IsNil)) - c.Assert(n3, Equals, int64(3)) - - // target close fails - reader4, writer4 := io.Pipe() - wg.Add(1) - go func() { - io.Copy(writer4, bytes.NewBufferString(data1)) - wg.Done() - }() - var failclose io.WriteCloser - failclose = &failClose{} - methods.On("getSourceReader", sourceURL, sourceConfig).Return(reader4, dataLen1, etag1, nil).Once() - methods.On("getTargetWriter", targetURL, targetConfig, etag1, dataLen1).Return(failclose, nil).Once() - err = doCopySingleSource(methods, sourceURL, targetURL, sourceConfig, targetConfig) - wg.Wait() - c.Assert(err, Not(IsNil)) -} - -func (s *CmdTestSuite) TestLsCmdWithBucket(c *C) { - sourceURL, err := getExpandedURL("http://example.com/bucket1/", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - data1 := "hello world 1" - dataLen1 := int64(len(data1)) - - data2 := "hello world 2" - dataLen2 := int64(len(data2)) - - contents := []*client.Content{ - {Name: "hello1", Time: time.Now(), Size: dataLen1}, - {Name: "hello2", Time: time.Now(), Size: dataLen2}, - } - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - contentCh := make(chan client.ContentOnChannel) - go func() { - defer close(contentCh) - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - }() - cl1.On("ListRecursive").Return(contentCh).Once() - err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestLsCmdWithFilePath(c *C) { - sourceURL, err := getExpandedURL("foo", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - data1 := "hello world 1" - dataLen1 := int64(len(data1)) - - data2 := "hello world 2" - dataLen2 := int64(len(data2)) - - contents := []*client.Content{ - {Name: "hello1", Time: time.Now(), Size: dataLen1}, - {Name: "hello2", Time: time.Now(), Size: dataLen2}, - } - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - - contentCh := make(chan client.ContentOnChannel) - go func() { - defer close(contentCh) - for _, content := range contents { - contentCh <- client.ContentOnChannel{ - Content: content, - Err: nil, - } - } - }() - cl1.On("ListRecursive").Return(contentCh).Once() - err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestLsCmdListsBuckets(c *C) { - sourceURL, err := getExpandedURL("http://example.com", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - buckets := []*client.Content{ - {Name: "bucket1", Time: time.Now()}, - {Name: "bucket2", Time: time.Now()}, - } - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - contentCh := make(chan client.ContentOnChannel) - go func() { - defer close(contentCh) - for _, bucket := range buckets { - contentCh <- client.ContentOnChannel{ - Content: bucket, - Err: nil, - } - } - }() - cl1.On("ListRecursive").Return(contentCh).Once() - err = doListRecursiveCmd(methods, sourceURL, sourceConfig, false) - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestMbCmd(c *C) { - targetURL, err := getExpandedURL("http://example.com/bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket").Return(nil).Once() - msg, err := doMakeBucketCmd(methods, targetURL, targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestAccessCmd(c *C) { - targetURL, err := getExpandedURL("http://example.com/bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "private").Return(nil).Once() - msg, err := doUpdateAccessCmd(methods, targetURL, "private", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "public").Return(nil).Once() - msg, err = doUpdateAccessCmd(methods, targetURL, "public", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "readonly").Return(nil).Once() - msg, err = doUpdateAccessCmd(methods, targetURL, "readonly", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestAccessCmdFailures(c *C) { - targetURL, err := getExpandedURL("http://example.com/bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(nil, errors.New("Expected Failure")).Once() - msg, err := doMakeBucketCmd(methods, targetURL, targetConfig, false) - c.Assert(len(msg) > 0, Equals, true) - c.Assert(err, Not(IsNil)) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "private").Return(&net.DNSError{}).Once() - cl1.On("PutBucketACL", "private").Return(nil).Once() - msg, err = doUpdateAccessCmd(methods, targetURL, "private", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - // we use <= rather than < since the original doesn't count in the retry - retries := globalMaxRetryFlag - globalMaxRetryFlag = 1 - for i := 0; i <= globalMaxRetryFlag; i++ { - err := new(net.OpError) - err.Op = "dial" - err.Net = "tcp" - err.Err = errors.New("Another expected error") - cl1.On("PutBucketACL", "private").Return(err).Once() - } - msg, err = doUpdateAccessCmd(methods, targetURL, "private", targetConfig, false) - globalMaxRetryFlag = retries - c.Assert(len(msg) > 0, Equals, true) - c.Assert(err, Not(IsNil)) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestMbCmdFailures(c *C) { - targetURL, err := getExpandedURL("http://example.com/bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(nil, errors.New("Expected Failure")).Once() - msg, err := doMakeBucketCmd(methods, targetURL, targetConfig, false) - c.Assert(len(msg) > 0, Equals, true) - c.Assert(err, Not(IsNil)) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket").Return(&net.DNSError{}).Once() - cl1.On("PutBucket").Return(nil).Once() - msg, err = doMakeBucketCmd(methods, targetURL, targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - // we use <= rather than < since the original doesn't count in the retry - retries := globalMaxRetryFlag - globalMaxRetryFlag = 1 - for i := 0; i <= globalMaxRetryFlag; i++ { - err := new(net.OpError) - err.Op = "dial" - err.Net = "tcp" - err.Err = errors.New("Another expected error") - cl1.On("PutBucket").Return(err).Once() - } - msg, err = doMakeBucketCmd(methods, targetURL, targetConfig, false) - globalMaxRetryFlag = retries - c.Assert(len(msg) > 0, Equals, true) - c.Assert(err, Not(IsNil)) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestAccessCmdOnFile(c *C) { - targetURL, err := getExpandedURL("bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "private").Return(nil).Once() - msg, err := doUpdateAccessCmd(methods, targetURL, "private", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "public").Return(nil).Once() - msg, err = doUpdateAccessCmd(methods, targetURL, "public", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucketACL", "readonly").Return(nil).Once() - msg, err = doUpdateAccessCmd(methods, targetURL, "readonly", targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestMbCmdOnFile(c *C) { - targetURL, err := getExpandedURL("bucket1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - - targetURLConfigMap := make(map[string]*hostConfig) - targetConfig := new(hostConfig) - targetConfig.AccessKeyID = "" - targetConfig.SecretAccessKey = "" - targetURLConfigMap[targetURL] = targetConfig - - methods.On("getNewClient", targetURL, targetConfig, false).Return(cl1, nil).Once() - cl1.On("PutBucket").Return(nil).Once() - msg, err := doMakeBucketCmd(methods, targetURL, targetConfig, false) - c.Assert(msg, Equals, "") - c.Assert(err, IsNil) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestCatCmdObject(c *C) { - sourceURL, err := getExpandedURL("http://example.com/bucket1/object1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - cl2 := &clientMocks.Client{} - - data1 := "hello world 1" - binarySum1 := md5.Sum([]byte(data1)) - etag1 := hex.EncodeToString(binarySum1[:]) - dataLen1 := int64(len(data1)) - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - sourceReader, sourceWriter := io.Pipe() - var resultBuffer bytes.Buffer - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - io.Copy(sourceWriter, bytes.NewBufferString(data1)) - sourceWriter.Close() - wg.Done() - }() - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - cl1.On("Get").Return(sourceReader, dataLen1, etag1, nil) - hasher := md5.New() - mw := io.MultiWriter(os.Stdout, hasher) - _, err = io.CopyN(mw, sourceReader, dataLen1) - c.Assert(err, IsNil) - msg, err := doCatCmd(methods, sourceURLConfigMap, false) - c.Assert(msg, Not(Equals), "") - c.Assert(err, Not(IsNil)) - - // without this there will be data races - wg.Wait() - c.Assert(data1, Not(Equals), resultBuffer.String()) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) - cl2.AssertExpectations(c) -} - -func (s *CmdTestSuite) TestCatCmdFile(c *C) { - sourceURL, err := getExpandedURL("object1", nil) - c.Assert(err, IsNil) - - methods := &MockclientMethods{} - cl1 := &clientMocks.Client{} - cl2 := &clientMocks.Client{} - - data1 := "hello world 1" - binarySum1 := md5.Sum([]byte(data1)) - etag1 := hex.EncodeToString(binarySum1[:]) - dataLen1 := int64(len(data1)) - - sourceURLConfigMap := make(map[string]*hostConfig) - sourceConfig := new(hostConfig) - sourceConfig.AccessKeyID = "" - sourceConfig.SecretAccessKey = "" - sourceURLConfigMap[sourceURL] = sourceConfig - - sourceReader, sourceWriter := io.Pipe() - var resultBuffer bytes.Buffer - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - io.Copy(sourceWriter, bytes.NewBufferString(data1)) - sourceWriter.Close() - wg.Done() - }() - - methods.On("getNewClient", sourceURL, sourceConfig, false).Return(cl1, nil).Once() - cl1.On("Get").Return(sourceReader, dataLen1, etag1, nil) - hasher := md5.New() - mw := io.MultiWriter(os.Stdout, hasher) - _, err = io.CopyN(mw, sourceReader, dataLen1) - c.Assert(err, IsNil) - msg, err := doCatCmd(methods, sourceURLConfigMap, false) - c.Assert(msg, Not(Equals), "") - c.Assert(err, Not(IsNil)) - - // with this there will be data races - wg.Wait() - c.Assert(data1, Not(Equals), resultBuffer.String()) - - methods.AssertExpectations(c) - cl1.AssertExpectations(c) - cl2.AssertExpectations(c) -} - func mustGetMcConfigDir() string { dir, _ := getMcConfigDir() return dir } +func (s *CmdTestSuite) TestGetNewClient(c *C) { + _, err := getNewClient("http://example.com/bucket1", &hostConfig{}, false) + c.Assert(err, IsNil) + + _, err = getNewClient("file", &hostConfig{}, false) + c.Assert(err, IsNil) + + _, err = getNewClient("%", &hostConfig{}, false) + c.Assert(err, Not(IsNil)) +} + +func (s *CmdTestSuite) TestNewConfigV1(c *C) { + root, err := ioutil.TempDir(os.TempDir(), "mc-") + c.Assert(err, IsNil) + defer os.RemoveAll(root) + + conf := newConfig() + configFile := path.Join(root, "config.json") + err = conf.Save(configFile) + c.Assert(err, IsNil) + + confNew := newConfigV1() + config := quick.New(confNew) + err = config.Load(configFile) + c.Assert(err, IsNil) + data := config.Data().(*configV1) + + type aliases struct { + name string + url string + } + + want := []aliases{ + { + "s3", + "https://s3.amazonaws.com", + }, + { + "play", + "http://play.minio.io:9000", + }, + { + "localhost", + "http://localhost:9000", + }, + } + for _, alias := range want { + url, ok := data.Aliases[alias.name] + c.Assert(ok, Equals, true) + c.Assert(url, Equals, alias.url) + } + +} + +func (s *CmdTestSuite) TestValidACL(c *C) { + acl := bucketACL("private") + c.Assert(acl.isValidBucketACL(), Equals, true) +} + +func (s *CmdTestSuite) TestInvalidACL(c *C) { + acl := bucketACL("invalid") + c.Assert(acl.isValidBucketACL(), Equals, false) +} + func (s *CmdTestSuite) TestGetMcConfigDir(c *C) { u, err := user.Current() c.Assert(err, IsNil) diff --git a/clientmethods.go b/common-methods.go similarity index 71% rename from clientmethods.go rename to common-methods.go index 877b0513..7c76152b 100644 --- a/clientmethods.go +++ b/common-methods.go @@ -26,25 +26,17 @@ import ( "github.com/minio-io/minio/pkg/iodine" ) -// clientMethods interface for mock tests -type clientMethods interface { - cpMethods - getNewClient(urlStr string, config *hostConfig, debug bool) (clnt client.Client, err error) -} - -type mcClientMethods struct{} - +/* type sourceReader struct { reader io.ReadCloser length int64 md5hex string } +*/ // getSourceReader - -func (methods mcClientMethods) getSourceReader(sourceURL string, sourceConfig *hostConfig) ( - reader io.ReadCloser, length int64, md5hex string, err error) { - - sourceClnt, err := methods.getNewClient(sourceURL, sourceConfig, globalDebugFlag) +func getSourceReader(sourceURL string, sourceConfig *hostConfig) (reader io.ReadCloser, length int64, md5hex string, err error) { + sourceClnt, err := getNewClient(sourceURL, sourceConfig, globalDebugFlag) if err != nil { return nil, 0, "", iodine.New(err, map[string]string{"failedURL": sourceURL}) } @@ -55,8 +47,8 @@ func (methods mcClientMethods) getSourceReader(sourceURL string, sourceConfig *h } // getTargetWriter - -func (methods mcClientMethods) getTargetWriter(targetURL string, targetConfig *hostConfig, md5hex string, length int64) (io.WriteCloser, error) { - targetClnt, err := methods.getNewClient(targetURL, targetConfig, globalDebugFlag) +func getTargetWriter(targetURL string, targetConfig *hostConfig, md5hex string, length int64) (io.WriteCloser, error) { + targetClnt, err := getNewClient(targetURL, targetConfig, globalDebugFlag) if err != nil { return nil, iodine.New(err, nil) } @@ -64,7 +56,7 @@ func (methods mcClientMethods) getTargetWriter(targetURL string, targetConfig *h } // getNewClient gives a new client interface -func (methods mcClientMethods) getNewClient(urlStr string, auth *hostConfig, debug bool) (clnt client.Client, err error) { +func getNewClient(urlStr string, auth *hostConfig, debug bool) (clnt client.Client, err error) { t := client.GetType(urlStr) switch t { case client.Object: // Minio and S3 compatible object storage diff --git a/cp-methods.go b/cp-methods.go index e518620b..5f8f71f2 100644 --- a/cp-methods.go +++ b/cp-methods.go @@ -22,17 +22,17 @@ import ( "github.com/minio-io/minio/pkg/iodine" ) -// cpMethods - methods only valid for cp -type cpMethods interface { - getSourceReader(sourceURL string, sourceConfig *hostConfig) (reader io.ReadCloser, length int64, md5hex string, err error) - getTargetWriter(targetURL string, targetConfig *hostConfig, md5Hex string, length int64) (io.WriteCloser, error) +type sourceReader struct { + reader io.ReadCloser + length int64 + md5hex string } // getSourceReaders - -func getSourceReaders(methods cpMethods, sourceURLConfigMap map[string]*hostConfig) (map[string]sourceReader, error) { +func getSourceReaders(sourceURLConfigMap map[string]*hostConfig) (map[string]sourceReader, error) { sourceURLReaderMap := make(map[string]sourceReader) for sourceURL, sourceConfig := range sourceURLConfigMap { - reader, length, md5hex, err := methods.getSourceReader(sourceURL, sourceConfig) + reader, length, md5hex, err := getSourceReader(sourceURL, sourceConfig) if err != nil { for _, sourceReader := range sourceURLReaderMap { sourceReader.reader.Close() diff --git a/cp.go b/cp.go index 490a0da9..3225b901 100644 --- a/cp.go +++ b/cp.go @@ -27,8 +27,8 @@ import ( /// mc cp - related internal functions // doCopy -func doCopy(methods clientMethods, reader io.ReadCloser, md5hex string, length int64, targetURL string, targetConfig *hostConfig) error { - writeCloser, err := methods.getTargetWriter(targetURL, targetConfig, md5hex, length) +func doCopy(reader io.ReadCloser, md5hex string, length int64, targetURL string, targetConfig *hostConfig) error { + writeCloser, err := getTargetWriter(targetURL, targetConfig, md5hex, length) if err != nil { return iodine.New(err, nil) } @@ -60,8 +60,8 @@ func doCopy(methods clientMethods, reader io.ReadCloser, md5hex string, length i } // doCopySingleSource -func doCopySingleSource(methods clientMethods, sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { - reader, length, md5hex, err := methods.getSourceReader(sourceURL, sourceConfig) +func doCopySingleSource(sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { + reader, length, md5hex, err := getSourceReader(sourceURL, sourceConfig) if err != nil { return iodine.New(err, nil) } @@ -69,19 +69,19 @@ func doCopySingleSource(methods clientMethods, sourceURL, targetURL string, sour newTargetURL, err := getNewTargetURL(targetURL, sourceURL) switch iodine.ToError(err).(type) { case errIsNotFolder: - return doCopy(methods, reader, md5hex, length, targetURL, targetConfig) + return doCopy(reader, md5hex, length, targetURL, targetConfig) case errIsNotBucket: - return doCopy(methods, reader, md5hex, length, targetURL, targetConfig) + return doCopy(reader, md5hex, length, targetURL, targetConfig) case nil: - return doCopy(methods, reader, md5hex, length, newTargetURL, targetConfig) + return doCopy(reader, md5hex, length, newTargetURL, targetConfig) default: return iodine.New(err, nil) } } // doCopySingleSourceRecursive -func doCopySingleSourceRecursive(methods clientMethods, sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { - sourceClnt, err := methods.getNewClient(sourceURL, sourceConfig, globalDebugFlag) +func doCopySingleSourceRecursive(sourceURL, targetURL string, sourceConfig, targetConfig *hostConfig) error { + sourceClnt, err := getNewClient(sourceURL, sourceConfig, globalDebugFlag) if err != nil { return iodine.New(err, nil) } @@ -90,7 +90,7 @@ func doCopySingleSourceRecursive(methods clientMethods, sourceURL, targetURL str continue } newSourceURL, newTargetURL := getNewURLRecursive(sourceURL, targetURL, contentCh.Content.Name) - if err := doCopySingleSource(methods, newSourceURL, newTargetURL, sourceConfig, targetConfig); err != nil { + if err := doCopySingleSource(newSourceURL, newTargetURL, sourceConfig, targetConfig); err != nil { // verify for directory related errors, if "open" failed on directories ignore those errors switch e := iodine.ToError(err).(type) { case *os.PathError: @@ -111,8 +111,8 @@ func doCopySingleSourceRecursive(methods clientMethods, sourceURL, targetURL str } // doCopyMultipleSources - -func doCopyMultipleSources(methods clientMethods, sourceURLConfigMap map[string]*hostConfig, targetURL string, targetConfig *hostConfig) error { - sourceURLReaderMap, err := getSourceReaders(methods, sourceURLConfigMap) +func doCopyMultipleSources(sourceURLConfigMap map[string]*hostConfig, targetURL string, targetConfig *hostConfig) error { + sourceURLReaderMap, err := getSourceReaders(sourceURLConfigMap) if err != nil { return iodine.New(err, nil) } @@ -121,7 +121,7 @@ func doCopyMultipleSources(methods clientMethods, sourceURLConfigMap map[string] if err != nil { return iodine.New(err, nil) } - err = doCopy(methods, sourceReader.reader, sourceReader.md5hex, sourceReader.length, newTargetURL, targetConfig) + err = doCopy(sourceReader.reader, sourceReader.md5hex, sourceReader.length, newTargetURL, targetConfig) if err != nil { return iodine.New(err, map[string]string{"Source": sourceURL}) } diff --git a/main.go b/main.go index 9c562ba6..97ae9781 100644 --- a/main.go +++ b/main.go @@ -18,7 +18,6 @@ package main import ( "fmt" - "io/ioutil" "os" "os/user" "runtime" @@ -29,14 +28,13 @@ import ( "github.com/minio-io/cli" "github.com/minio-io/mc/pkg/console" "github.com/minio-io/minio/pkg/iodine" - "github.com/minio-io/minio/pkg/utils/log" ) // Check for the environment early on and gracefully report. func checkConfig() { _, err := user.Current() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalln("Unable to determine current user") } @@ -48,7 +46,7 @@ func checkConfig() { // Ensures config file is sane _, err = getMcConfig() if err != nil { - log.Debug.Println(iodine.New(err, nil)) + console.Debugln(iodine.New(err, nil)) console.Fatalf("Unable to read config file: %s\n", mustGetMcConfigPath()) } } @@ -108,8 +106,7 @@ func main() { globalMaxRetryFlag = ctx.GlobalInt("retry") if globalDebugFlag { app.ExtraInfo = getSystemData() - } else { - log.Debug = log.New(ioutil.Discard, "", 0) + console.NoDebugPrint = false } themeName := ctx.GlobalString("theme") if console.IsValidTheme(themeName) { diff --git a/mock_clientmethods_test.go b/mock_clientmethods_test.go deleted file mode 100644 index 5e1ac420..00000000 --- a/mock_clientmethods_test.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "io" - - "github.com/minio-io/mc/pkg/client" - "github.com/stretchr/testify/mock" -) - -// MockclientMethods is a mock for testing, please ignore. -type MockclientMethods struct { - mock.Mock -} - -func (m *MockclientMethods) getSourceReader(urlStr string, auth *hostConfig) (io.ReadCloser, int64, string, error) { - ret := m.Called(urlStr, auth) - - var r0 io.ReadCloser - untypedR0 := ret.Get(0) - if untypedR0 != nil { - r0 = untypedR0.(io.ReadCloser) - } else { - r0 = nil - } - r1 := ret.Get(1).(int64) - r2 := ret.Get(2).(string) - r3 := ret.Error(3) - - return r0, r1, r2, r3 -} -func (m *MockclientMethods) getTargetWriter(urlStr string, auth *hostConfig, md5Hex string, length int64) (io.WriteCloser, error) { - ret := m.Called(urlStr, auth, md5Hex, length) - - var r0 io.WriteCloser - untypedR0 := ret.Get(0) - if untypedR0 != nil { - r0 = untypedR0.(io.WriteCloser) - } else { - r0 = nil - } - r1 := ret.Error(1) - - return r0, r1 -} -func (m *MockclientMethods) getNewClient(urlStr string, auth *hostConfig, debug bool) (client.Client, error) { - ret := m.Called(urlStr, auth, debug) - - var r0 client.Client - untypedR0 := ret.Get(0) - if untypedR0 != nil { - r0 = untypedR0.(client.Client) - } else { - r0 = nil - } - r1 := ret.Error(1) - - return r0, r1 -} diff --git a/pkg/client/client.go b/pkg/client/client.go index 07b35aa4..0da6d0ab 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -26,7 +26,7 @@ import ( // Client - client interface type Client interface { - MultipartUpload + // MultipartUpload - TODO // Common operations Stat() (content *Content, err error) @@ -44,13 +44,13 @@ type Client interface { } // MultipartUpload - multi part upload interface -type MultipartUpload interface { - InitiateMultiPartUpload() (objectID string, err error) - UploadPart(uploadID string, body io.ReadSeeker, contentLength, partNumber int64) (md5hex string, err error) - CompleteMultiPartUpload(uploadID string) (location, md5hex string, err error) - AbortMultiPartUpload(uploadID string) error - ListParts(uploadID string) (contents *PartContents, err error) -} +//type MultipartUpload interface { +// InitiateMultiPartUpload() (objectID string, err error) +// UploadPart(uploadID string, body io.ReadSeeker, contentLength, partNumber int64) (md5hex string, err error) +// CompleteMultiPartUpload(uploadID string) (location, md5hex string, err error) +// AbortMultiPartUpload(uploadID string) error +// ListParts(uploadID string) (contents *PartContents, err error) +//} // Part - part xml response type Part struct { diff --git a/pkg/client/fs/fs_multipart_put.go b/pkg/client/fs/fs_multipart_put.go deleted file mode 100644 index c72bd765..00000000 --- a/pkg/client/fs/fs_multipart_put.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package fs - -import ( - "io" - - "github.com/minio-io/mc/pkg/client" - "github.com/minio-io/minio/pkg/iodine" -) - -// Multipart object upload handlers - -// InitiateMultiPartUpload - -func (c *fsClient) InitiateMultiPartUpload() (objectID string, err error) { - return "", iodine.New(client.APINotImplemented{API: "InitiateMultiPartUpload"}, nil) -} - -// UploadPart - -func (c *fsClient) UploadPart(uploadID string, body io.ReadSeeker, contentLength, partNumber int64) (md5hex string, err error) { - return "", iodine.New(client.APINotImplemented{API: "UploadPart"}, nil) -} - -// CompleteMultiPartUpload - -func (c *fsClient) CompleteMultiPartUpload(uploadID string) (location, md5hex string, err error) { - return "", "", iodine.New(client.APINotImplemented{API: "CompleteMultiPartUpload"}, nil) -} - -// AbortMultiPartUpload - -func (c *fsClient) AbortMultiPartUpload(uploadID string) error { - return iodine.New(client.APINotImplemented{API: "AbortMultiPartUpload"}, nil) -} - -// ListParts - -func (c *fsClient) ListParts(uploadID string) (contents *client.PartContents, err error) { - return nil, iodine.New(client.APINotImplemented{API: "ListParts"}, nil) -} diff --git a/pkg/client/mocks/Client.go b/pkg/client/mocks/Client.go deleted file mode 100644 index 99587390..00000000 --- a/pkg/client/mocks/Client.go +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package mocks - -import ( - "io" - - "github.com/minio-io/mc/pkg/client" - "github.com/stretchr/testify/mock" -) - -// Client mock -type Client struct { - mock.Mock -} - -// PutBucket is a mock method -func (m *Client) PutBucket() error { - ret := m.Called() - - r0 := ret.Error(0) - - return r0 -} - -// PutBucketACL is a mock method -func (m *Client) PutBucketACL(acl string) error { - ret := m.Called(acl) - - r0 := ret.Error(0) - - return r0 -} - -// Stat is a mock method -func (m *Client) Stat() (*client.Content, error) { - ret := m.Called() - - var r0 *client.Content - if ret.Get(0) != nil { - r0 = ret.Get(0).(*client.Content) - } - - r1 := ret.Error(1) - - return r0, r1 -} - -// List is a mock method -func (m *Client) List() <-chan client.ContentOnChannel { - ret := m.Called() - r0 := ret.Get(0).(chan client.ContentOnChannel) - return r0 -} - -// ListRecursive is a mock method -func (m *Client) ListRecursive() <-chan client.ContentOnChannel { - ret := m.Called() - r0 := ret.Get(0).(chan client.ContentOnChannel) - return r0 -} - -// Get is a mock method -func (m *Client) Get() (io.ReadCloser, int64, string, error) { - ret := m.Called() - - r0 := ret.Get(0).(io.ReadCloser) - r1 := ret.Get(1).(int64) - r2 := ret.Get(2).(string) - r3 := ret.Error(3) - - return r0, r1, r2, r3 -} - -// GetPartial is a mock method -func (m *Client) GetPartial(offset int64, length int64) (io.ReadCloser, int64, string, error) { - ret := m.Called(offset, length) - - r0 := ret.Get(0).(io.ReadCloser) - r1 := ret.Get(1).(int64) - r2 := ret.Get(2).(string) - r3 := ret.Error(3) - - return r0, r1, r2, r3 -} - -// Put is a mock method -func (m *Client) Put(md5 string, size int64) (io.WriteCloser, error) { - ret := m.Called(md5, size) - - r0 := ret.Get(0).(io.WriteCloser) - r1 := ret.Error(1) - - return r0, r1 -} - -// InitiateMultiPartUpload is a mock method -func (m *Client) InitiateMultiPartUpload() (string, error) { - ret := m.Called() - - r0 := ret.Get(0).(string) - r1 := ret.Error(1) - - return r0, r1 -} - -// UploadPart is a mock method -func (m *Client) UploadPart(uploadID string, body io.ReadSeeker, contentLength, partNumber int64) (string, error) { - ret := m.Called(uploadID, body, contentLength, partNumber) - - r0 := ret.Get(0).(string) - r1 := ret.Error(1) - - return r0, r1 -} - -// CompleteMultiPartUpload is a mock method -func (m *Client) CompleteMultiPartUpload(uploadID string) (string, string, error) { - ret := m.Called(uploadID) - - r0 := ret.Get(0).(string) - r1 := ret.Get(1).(string) - r2 := ret.Error(2) - - return r0, r1, r2 -} - -// AbortMultiPartUpload is a mock method -func (m *Client) AbortMultiPartUpload(uploadID string) error { - ret := m.Called(uploadID) - - r0 := ret.Error(0) - - return r0 -} - -// ListParts is a mock method -func (m *Client) ListParts(uploadID string) (*client.PartContents, error) { - ret := m.Called(uploadID) - - var r0 *client.PartContents - if ret.Get(0) != nil { - r0 = ret.Get(0).(*client.PartContents) - } - r1 := ret.Error(1) - - return r0, r1 -} diff --git a/pkg/client/mocks/HTTPTracer.go b/pkg/client/mocks/HTTPTracer.go deleted file mode 100644 index 5d03c90f..00000000 --- a/pkg/client/mocks/HTTPTracer.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package mocks - -import ( - "net/http" - - "github.com/stretchr/testify/mock" -) - -// httpTracer is a mock object -type httpTracer struct { - mock.Mock -} - -// Request is a mock method -func (m *httpTracer) Request(req *http.Request) error { - ret := m.Called(req) - - r0 := ret.Error(0) - - return r0 -} - -// Response is a mock method -func (m *httpTracer) Response(res *http.Response) error { - ret := m.Called(res) - - r0 := ret.Error(0) - - return r0 -} diff --git a/pkg/client/mocks/MultipartUpload.go b/pkg/client/mocks/MultipartUpload.go deleted file mode 100644 index 50e1fb47..00000000 --- a/pkg/client/mocks/MultipartUpload.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package mocks diff --git a/pkg/client/s3/bucket.go b/pkg/client/s3/bucket.go index 78fcf104..6c3c45df 100644 --- a/pkg/client/s3/bucket.go +++ b/pkg/client/s3/bucket.go @@ -70,7 +70,7 @@ func (c *s3Client) PutBucket() error { } if res != nil { if res.StatusCode != http.StatusOK { - return iodine.New(NewError(res), nil) + return iodine.New(ResponseToError(res), nil) } } defer res.Body.Close() @@ -114,7 +114,7 @@ func (c *s3Client) PutBucketACL(acl string) error { } if res != nil { if res.StatusCode != http.StatusOK { - return iodine.New(NewError(res), nil) + return iodine.New(ResponseToError(res), nil) } } defer res.Body.Close() diff --git a/pkg/client/s3/bucket_object_metadata.go b/pkg/client/s3/bucket_object_metadata.go index 65c8be8a..4653437e 100644 --- a/pkg/client/s3/bucket_object_metadata.go +++ b/pkg/client/s3/bucket_object_metadata.go @@ -63,7 +63,7 @@ func (c *s3Client) getBucketMetadata(bucket string) (content *client.Content, er case http.StatusMovedPermanently: return content, nil default: - return nil, iodine.New(NewError(res), nil) + return nil, iodine.New(ResponseToError(res), nil) } } @@ -109,6 +109,6 @@ func (c *s3Client) getObjectMetadata(bucket, object string) (content *client.Con content.FileType = 0 return content, nil default: - return nil, iodine.New(NewError(res), nil) + return nil, iodine.New(ResponseToError(res), nil) } } diff --git a/pkg/client/s3/bucket_routines.go b/pkg/client/s3/bucket_routines.go index 5a37dd54..e57484c3 100644 --- a/pkg/client/s3/bucket_routines.go +++ b/pkg/client/s3/bucket_routines.go @@ -146,7 +146,7 @@ func (c *s3Client) decodeBucketResults(queryURL string) (*listBucketResults, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, iodine.New(NewError(res), nil) + return nil, iodine.New(ResponseToError(res), nil) } var logbuf bytes.Buffer err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(bres) @@ -271,8 +271,7 @@ func (c *s3Client) listBuckets() ([]*client.Content, error) { } if res != nil { if res.StatusCode != http.StatusOK { - err = NewError(res) - return nil, iodine.New(err, nil) + return nil, iodine.New(ResponseToError(res), nil) } } defer res.Body.Close() diff --git a/pkg/client/s3/client_test.go b/pkg/client/s3/client_test.go index 1ca0d4bd..459e1016 100644 --- a/pkg/client/s3/client_test.go +++ b/pkg/client/s3/client_test.go @@ -95,7 +95,7 @@ func (s *MySuite) TestError(c *C) { res := "\nAccessDeniedAccess Denied/mybucket/myphoto.jpgF19772218238A85AGuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD" response := new(http.Response) response.Body = ioutil.NopCloser(strings.NewReader(res)) - err := NewError(response) + err := ResponseToError(response) c.Assert(err, Not(IsNil)) c.Assert(err.Error(), Equals, "Access Denied") } diff --git a/pkg/client/s3/common.go b/pkg/client/s3/common.go index 4cb43c86..c2b254ed 100644 --- a/pkg/client/s3/common.go +++ b/pkg/client/s3/common.go @@ -17,12 +17,9 @@ package s3 import ( - "io/ioutil" "net/http" "net/url" - "github.com/awslabs/aws-sdk-go/aws" - "github.com/awslabs/aws-sdk-go/service/s3" "github.com/minio-io/mc/pkg/client" ) @@ -41,15 +38,10 @@ func New(config *Config) client.Client { } else { transport = http.DefaultTransport } - awsConf := aws.DefaultConfig - awsConf.Credentials = aws.Creds(config.AccessKeyID, config.SecretAccessKey, "") - awsConf.HTTPClient = &http.Client{Transport: transport} - awsConf.Logger = ioutil.Discard s3c := &s3Client{ &Meta{ Config: config, Transport: transport, - S3: s3.New(awsConf), }, u, } return s3c diff --git a/pkg/client/s3/definitions.go b/pkg/client/s3/definitions.go index e697b87f..09c552b5 100644 --- a/pkg/client/s3/definitions.go +++ b/pkg/client/s3/definitions.go @@ -1,11 +1,25 @@ +/* + * Minio Client (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package s3 import ( "net/http" "net/url" "time" - - "github.com/awslabs/aws-sdk-go/service/s3" ) // @@ -35,7 +49,6 @@ type listBucketResults struct { // Meta holds Amazon S3 client credentials and flags. type Meta struct { *Config - *s3.S3 Transport http.RoundTripper // or nil for the default behavior } diff --git a/pkg/client/s3/errors.go b/pkg/client/s3/errors.go index 2c2887af..56ee6fa3 100644 --- a/pkg/client/s3/errors.go +++ b/pkg/client/s3/errors.go @@ -17,16 +17,11 @@ package s3 import ( - "fmt" + "encoding/xml" "net/http" "strconv" - - "github.com/clbanning/mxj" - "github.com/minio-io/minio/pkg/iodine" ) -/// ACL related errors - // InvalidACL - acl invalid type InvalidACL struct { ACL string @@ -113,7 +108,6 @@ func (e InvalidQueryURL) Error() string { } /* **** SAMPLE ERROR RESPONSE **** -s3.ListBucket: status 403: AccessDenied @@ -124,26 +118,27 @@ s3.ListBucket: status 403: */ -// Error is the type returned by some API operations. -type Error struct { - response *http.Response // response headers - responseMap mxj.Map // Keys: Code, Message, Resource, RequestId, HostId +// ErrorResponse is the type returned by some API operations. +type ErrorResponse struct { + Code string + Message string + Resource string + RequestID string + HostID string } -// NewError returns a new initialized S3.Error structure -func NewError(res *http.Response) error { - var err error - s3Err := new(Error) - s3Err.response = res - s3Err.responseMap, err = mxj.NewMapXmlReader(res.Body) +// ResponseToError returns a new encoded ErrorResponse structure +func ResponseToError(res *http.Response) error { + var respError ErrorResponse + decoder := xml.NewDecoder(res.Body) + err := decoder.Decode(&respError) if err != nil { - return iodine.New(err, nil) + return err } - return s3Err + return respError } // Error formats HTTP error string -func (e *Error) Error() string { - message, _ := e.responseMap.ValuesForKey("Message") - return fmt.Sprintf("%s", message[0]) +func (e ErrorResponse) Error() string { + return e.Message } diff --git a/pkg/client/s3/object_get.go b/pkg/client/s3/object_get.go index ceba0ab1..2d4a17fe 100644 --- a/pkg/client/s3/object_get.go +++ b/pkg/client/s3/object_get.go @@ -71,7 +71,7 @@ func (c *s3Client) Get() (body io.ReadCloser, size int64, md5 string, err error) } if res.StatusCode != http.StatusOK { - return nil, 0, "", iodine.New(NewError(res), nil) + return nil, 0, "", iodine.New(ResponseToError(res), nil) } md5sum := strings.Trim(res.Header.Get("ETag"), "\"") // trim off the erroneous double quotes return res.Body, res.ContentLength, md5sum, nil @@ -99,6 +99,6 @@ func (c *s3Client) GetPartial(offset, length int64) (body io.ReadCloser, size in case http.StatusOK, http.StatusPartialContent: return res.Body, res.ContentLength, res.Header.Get("ETag"), nil default: - return nil, 0, "", iodine.New(NewError(res), nil) + return nil, 0, "", iodine.New(ResponseToError(res), nil) } } diff --git a/pkg/client/s3/object_multipart_put.go b/pkg/client/s3/object_multipart_put.go deleted file mode 100644 index 380eb54a..00000000 --- a/pkg/client/s3/object_multipart_put.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Minio Client (C) 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this fs except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package s3 - -import ( - "io" - - "github.com/awslabs/aws-sdk-go/service/s3" - "github.com/minio-io/mc/pkg/client" - "github.com/minio-io/minio/pkg/iodine" -) - -// Multipart object upload handlers - -// InitiateMultiPartUpload - start multipart upload session -func (c *s3Client) InitiateMultiPartUpload() (uploadID string, err error) { - bucket, object := c.url2BucketAndObject() - - multiparthUploadInput := new(s3.CreateMultipartUploadInput) - multiparthUploadInput.Bucket = &bucket - multiparthUploadInput.Key = &object - multiparthUploadOutput, err := c.S3.CreateMultipartUpload(multiparthUploadInput) - if err != nil { - return "", iodine.New(err, nil) - } - return *multiparthUploadOutput.UploadID, nil -} - -// UploadPart - start uploading individual parts -func (c *s3Client) UploadPart(uploadID string, body io.ReadSeeker, contentLength, partNumber int64) (md5hex string, err error) { - bucket, object := c.url2BucketAndObject() - - uploadPartInput := new(s3.UploadPartInput) - uploadPartInput.Bucket = &bucket - uploadPartInput.Key = &object - uploadPartInput.Body = body - uploadPartInput.PartNumber = &partNumber - uploadPartInput.UploadID = &uploadID - uploadPartOutput, err := c.S3.UploadPart(uploadPartInput) - if err != nil { - return "", iodine.New(err, nil) - } - return *uploadPartOutput.ETag, nil -} - -// CompleteMultiPartUpload -func (c *s3Client) CompleteMultiPartUpload(uploadID string) (location, md5hex string, err error) { - bucket, object := c.url2BucketAndObject() - - completeMultiPartUploadInput := new(s3.CompleteMultipartUploadInput) - completeMultiPartUploadInput.Bucket = &bucket - completeMultiPartUploadInput.Key = &object - completeMultiPartUploadInput.UploadID = &uploadID - - completeMultiPartUploadOutput, err := c.S3.CompleteMultipartUpload(completeMultiPartUploadInput) - if err != nil { - return "", "", iodine.New(err, nil) - } - return *completeMultiPartUploadOutput.Location, *completeMultiPartUploadOutput.ETag, nil -} - -// AbortMultiPartUpload -func (c *s3Client) AbortMultiPartUpload(uploadID string) error { - bucket, object := c.url2BucketAndObject() - abortMultiPartUploadInput := new(s3.AbortMultipartUploadInput) - abortMultiPartUploadInput.Bucket = &bucket - abortMultiPartUploadInput.Key = &object - abortMultiPartUploadInput.UploadID = &uploadID - if _, err := c.S3.AbortMultipartUpload(abortMultiPartUploadInput); err != nil { - return iodine.New(err, nil) - } - return nil -} - -// ListParts -func (c *s3Client) ListParts(uploadID string) (contents *client.PartContents, err error) { - bucket, object := c.url2BucketAndObject() - listPartsInput := new(s3.ListPartsInput) - listPartsInput.Bucket = &bucket - listPartsInput.Key = &object - listPartsInput.UploadID = &uploadID - - listPartsOutput, err := c.S3.ListParts(listPartsInput) - if err != nil { - return nil, iodine.New(err, nil) - } - contents = new(client.PartContents) - contents.Key = *listPartsOutput.Key - contents.IsTruncated = *listPartsOutput.IsTruncated - contents.UploadID = *listPartsOutput.UploadID - for _, part := range listPartsOutput.Parts { - newPart := new(client.Part) - newPart.ETag = *part.ETag - newPart.LastModified = *part.LastModified - newPart.PartNumber = *part.PartNumber - newPart.Size = *part.Size - contents.Parts = append(contents.Parts, newPart) - } - return contents, nil - -} diff --git a/pkg/client/s3/object_put.go b/pkg/client/s3/object_put.go index c49023d6..61ee55c3 100644 --- a/pkg/client/s3/object_put.go +++ b/pkg/client/s3/object_put.go @@ -82,7 +82,7 @@ func (c *s3Client) Put(md5HexString string, size int64) (io.WriteCloser, error) return } if res.StatusCode != http.StatusOK { - err := iodine.New(NewError(res), nil) + err := iodine.New(ResponseToError(res), nil) r.CloseWithError(err) blockingWriter.Release(err) return diff --git a/pkg/console/console.go b/pkg/console/console.go index aeab9710..f0095b8b 100644 --- a/pkg/console/console.go +++ b/pkg/console/console.go @@ -28,6 +28,9 @@ import ( "github.com/minio-io/minio/pkg/iodine" ) +// NoDebugPrint defines if the input should be printed or not. By default it's set to true. +var NoDebugPrint = true + var ( mutex = &sync.RWMutex{} @@ -66,11 +69,23 @@ var ( Infof = func(f string, a ...interface{}) { printf(themesDB[currThemeName].Info, f, a...) } // Debug prints a debug message - Debug = func(a ...interface{}) { print(themesDB[currThemeName].Debug, a...) } + Debug = func(a ...interface{}) { + if !NoDebugPrint { + print(themesDB[currThemeName].Debug, a...) + } + } // Debugln prints a debug message with a new line - Debugln = func(a ...interface{}) { println(themesDB[currThemeName].Debug, a...) } + Debugln = func(a ...interface{}) { + if !NoDebugPrint { + println(themesDB[currThemeName].Debug, a...) + } + } // Debugf prints a debug message with formatting - Debugf = func(f string, a ...interface{}) { printf(themesDB[currThemeName].Debug, f, a...) } + Debugf = func(f string, a ...interface{}) { + if !NoDebugPrint { + printf(themesDB[currThemeName].Debug, f, a...) + } + } // File - File("foo.txt") File = themesDB[currThemeName].File.SprintfFunc() @@ -214,17 +229,18 @@ func SetTheme(themeName string) error { mutex.Lock() - currThemeName = themeName - theme := themesDB[currThemeName] - // Just another additional precaution to completely disable color. // Color theme is also necessary, because it does other useful things like exit-on-fatal.. - if currThemeName == "nocolor" { + switch currThemeName { + case "nocolor": color.NoColor = true - } else { + default: color.NoColor = false } + currThemeName = themeName + theme := themesDB[currThemeName] + // Error prints a error message Error = func(a ...interface{}) { print(theme.Error, a...) } // Errorln prints a error message with a new line @@ -240,11 +256,23 @@ func SetTheme(themeName string) error { Infof = func(f string, a ...interface{}) { printf(theme.Info, f, a...) } // Debug prints a debug message - Debug = func(a ...interface{}) { print(theme.Debug, a...) } + Debug = func(a ...interface{}) { + if !NoDebugPrint { + print(theme.Debug, a...) + } + } // Debugln prints a debug message with a new line - Debugln = func(a ...interface{}) { println(theme.Debug, a...) } + Debugln = func(a ...interface{}) { + if !NoDebugPrint { + println(theme.Debug, a...) + } + } // Debugf prints a debug message with formatting - Debugf = func(f string, a ...interface{}) { printf(theme.Debug, f, a...) } + Debugf = func(f string, a ...interface{}) { + if !NoDebugPrint { + printf(theme.Debug, f, a...) + } + } Dir = theme.Dir.SprintfFunc() File = theme.File.SprintfFunc()