Example #1
0
func ExampleS3_UploadPart() {
	svc := s3.New(nil)

	params := &s3.UploadPartInput{
		Bucket:               aws.String("BucketName"),        // Required
		Key:                  aws.String("ObjectKey"),         // Required
		PartNumber:           aws.Int64(1),                    // Required
		UploadId:             aws.String("MultipartUploadId"), // Required
		Body:                 bytes.NewReader([]byte("PAYLOAD")),
		ContentLength:        aws.Int64(1),
		RequestPayer:         aws.String("RequestPayer"),
		SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"),
		SSECustomerKey:       aws.String("SSECustomerKey"),
		SSECustomerKeyMD5:    aws.String("SSECustomerKeyMD5"),
	}
	resp, err := svc.UploadPart(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #2
0
func ExampleS3_PutBucketLifecycleConfiguration() {
	svc := s3.New(nil)

	params := &s3.PutBucketLifecycleConfigurationInput{
		Bucket: aws.String("BucketName"), // Required
		LifecycleConfiguration: &s3.BucketLifecycleConfiguration{
			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.Int64(1),
					},
					ID: aws.String("ID"),
					NoncurrentVersionExpiration: &s3.NoncurrentVersionExpiration{
						NoncurrentDays: aws.Int64(1),
					},
					NoncurrentVersionTransitions: []*s3.NoncurrentVersionTransition{
						{ // Required
							NoncurrentDays: aws.Int64(1),
							StorageClass:   aws.String("TransitionStorageClass"),
						},
						// More values...
					},
					Transitions: []*s3.Transition{
						{ // Required
							Date:         aws.Time(time.Now()),
							Days:         aws.Int64(1),
							StorageClass: aws.String("TransitionStorageClass"),
						},
						// More values...
					},
				},
				// More values...
			},
		},
	}
	resp, err := svc.PutBucketLifecycleConfiguration(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #3
0
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.Int64(1),
				},
				// More values...
			},
		},
		RequestPayer: aws.String("RequestPayer"),
	}
	resp, err := svc.CompleteMultipartUpload(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #4
0
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.Int64(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 err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
func BenchmarkCodegenIterator(b *testing.B) {
	reqNum := 0
	db := benchDb()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = benchResps[reqNum]
		reqNum++
	})

	input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error {
		page, _ := db.ListTablesRequest(input)
		for ; page != nil; page = page.NextPage() {
			page.Send()
			out := page.Data.(*dynamodb.ListTablesOutput)
			if result := fn(out, !page.HasNextPage()); page.Error != nil || !result {
				return page.Error
			}
		}
		return nil
	}

	for i := 0; i < b.N; i++ {
		reqNum = 0
		iter(func(p *dynamodb.ListTablesOutput, last bool) bool {
			return true
		})
	}
}
// Retrieve generates a new set of temporary credentials using STS.
func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {

	// Apply defaults where parameters are not set.
	if p.Client == nil {
		p.Client = sts.New(nil)
	}
	if p.RoleSessionName == "" {
		// Try to work out a role name that will hopefully end up unique.
		p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
	}
	if p.Duration == 0 {
		// Expire as often as AWS permits.
		p.Duration = 15 * time.Minute
	}

	roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{
		DurationSeconds: aws.Int64(int64(p.Duration / time.Second)),
		RoleArn:         aws.String(p.RoleARN),
		RoleSessionName: aws.String(p.RoleSessionName),
		ExternalId:      p.ExternalID,
	})

	if err != nil {
		return credentials.Value{}, err
	}

	// We will proactively generate new credentials before they expire.
	p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)

	return credentials.Value{
		AccessKeyID:     *roleOutput.Credentials.AccessKeyId,
		SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
		SessionToken:    *roleOutput.Credentials.SessionToken,
	}, nil
}
// Use DynamoDB methods for simplicity
func TestPaginationEachPage(t *testing.T) {
	db := dynamodb.New(nil)
	tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false

	reqNum := 0
	resps := []*dynamodb.ListTablesOutput{
		{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
		{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
		{TableNames: []*string{aws.String("Table5")}},
	}

	db.Handlers.Send.Clear() // mock sending
	db.Handlers.Unmarshal.Clear()
	db.Handlers.UnmarshalMeta.Clear()
	db.Handlers.ValidateResponse.Clear()
	db.Handlers.Build.PushBack(func(r *request.Request) {
		in := r.Params.(*dynamodb.ListTablesInput)
		if in == nil {
			tokens = append(tokens, "")
		} else if in.ExclusiveStartTableName != nil {
			tokens = append(tokens, *in.ExclusiveStartTableName)
		}
	})
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	req, _ := db.ListTablesRequest(params)
	err := req.EachPage(func(p interface{}, last bool) bool {
		numPages++
		for _, t := range p.(*dynamodb.ListTablesOutput).TableNames {
			pages = append(pages, *t)
		}
		if last {
			if gotToEnd {
				assert.Fail(t, "last=true happened twice")
			}
			gotToEnd = true
		}

		return true
	})

	assert.Equal(t, []string{"Table2", "Table4"}, tokens)
	assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages)
	assert.Equal(t, 3, numPages)
	assert.True(t, gotToEnd)
	assert.Nil(t, err)
}
Example #8
0
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.Int64(1),
		PartNumberMarker: aws.Int64(1),
		RequestPayer:     aws.String("RequestPayer"),
	}
	resp, err := svc.ListParts(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
func TestUploadPartCopyError(t *testing.T) {
	_, err := newCopyTestSvc(errMsg).UploadPartCopy(&s3.UploadPartCopyInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/doesnotexist.txt"),
		Key:        aws.String("destination.txt"),
		PartNumber: aws.Int64(0),
		UploadId:   aws.String("uploadID"),
	})

	require.Error(t, err)
	e := err.(awserr.Error)

	assert.Equal(t, "ErrorCode", e.Code())
	assert.Equal(t, "message body", e.Message())
}
func BenchmarkEachPageIterator(b *testing.B) {
	reqNum := 0
	db := benchDb()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = benchResps[reqNum]
		reqNum++
	})

	input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	for i := 0; i < b.N; i++ {
		reqNum = 0
		req, _ := db.ListTablesRequest(input)
		req.EachPage(func(p interface{}, last bool) bool {
			return true
		})
	}
}
func TestUploadPartCopySuccess(t *testing.T) {
	const successMsg = `
<?xml version="1.0" encoding="UTF-8"?>
<UploadPartCopyResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LastModified>2009-11-23T0:00:00Z</LastModified><ETag>&quot;1da64c7f13d1e8dbeaea40b905fd586c&quot;</ETag></CopyObjectResult>`

	res, err := newCopyTestSvc(successMsg).UploadPartCopy(&s3.UploadPartCopyInput{
		Bucket:     aws.String("bucketname"),
		CopySource: aws.String("bucketname/doesnotexist.txt"),
		Key:        aws.String("destination.txt"),
		PartNumber: aws.Int64(0),
		UploadId:   aws.String("uploadID"),
	})

	require.NoError(t, err)

	assert.Equal(t, fmt.Sprintf(`%q`, "1da64c7f13d1e8dbeaea40b905fd586c"), *res.CopyPartResult.ETag)
	assert.Equal(t, lastModifiedTime, *res.CopyPartResult.LastModified)
}
Example #12
0
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.Int64(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 err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #13
0
func ExampleS3_PutBucketCors() {
	svc := s3.New(nil)

	params := &s3.PutBucketCorsInput{
		Bucket: aws.String("BucketName"), // Required
		CORSConfiguration: &s3.CORSConfiguration{ // Required
			CORSRules: []*s3.CORSRule{ // Required
				{ // Required
					AllowedMethods: []*string{ // Required
						aws.String("AllowedMethod"), // Required
						// More values...
					},
					AllowedOrigins: []*string{ // Required
						aws.String("AllowedOrigin"), // Required
						// More values...
					},
					AllowedHeaders: []*string{
						aws.String("AllowedHeader"), // Required
						// More values...
					},
					ExposeHeaders: []*string{
						aws.String("ExposeHeader"), // Required
						// More values...
					},
					MaxAgeSeconds: aws.Int64(1),
				},
				// More values...
			},
		},
	}
	resp, err := svc.PutBucketCors(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
// Use DynamoDB methods for simplicity
func TestPaginationEarlyExit(t *testing.T) {
	db := dynamodb.New(nil)
	numPages, gotToEnd := 0, false

	reqNum := 0
	resps := []*dynamodb.ListTablesOutput{
		{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
		{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
		{TableNames: []*string{aws.String("Table5")}},
	}

	db.Handlers.Send.Clear() // mock sending
	db.Handlers.Unmarshal.Clear()
	db.Handlers.UnmarshalMeta.Clear()
	db.Handlers.ValidateResponse.Clear()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool {
		numPages++
		if numPages == 2 {
			return false
		}
		if last {
			if gotToEnd {
				assert.Fail(t, "last=true happened twice")
			}
			gotToEnd = true
		}
		return true
	})

	assert.Equal(t, 2, numPages)
	assert.False(t, gotToEnd)
	assert.Nil(t, err)
}
Example #15
0
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.Int64(1),
		Prefix:       aws.String("Prefix"),
	}
	resp, err := svc.ListObjects(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Example #16
0
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.Int64(1), // Required
		},
		VersionId: aws.String("ObjectVersionId"),
	}
	resp, err := svc.RestoreObject(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}