You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.3 KiB

5 years ago
  1. package basic
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "testing"
  7. "github.com/aws/aws-sdk-go/aws"
  8. "github.com/aws/aws-sdk-go/aws/awserr"
  9. "github.com/aws/aws-sdk-go/aws/session"
  10. "github.com/aws/aws-sdk-go/service/s3"
  11. )
  12. var (
  13. svc *s3.S3
  14. )
  15. func init() {
  16. // Initialize a session in us-west-2 that the SDK will use to load
  17. // credentials from the shared credentials file ~/.aws/credentials.
  18. sess, err := session.NewSession(&aws.Config{
  19. Region: aws.String("us-west-2"),
  20. Endpoint: aws.String("localhost:8333"),
  21. DisableSSL: aws.Bool(true),
  22. })
  23. if err != nil {
  24. exitErrorf("create session, %v", err)
  25. }
  26. // Create S3 service client
  27. svc = s3.New(sess)
  28. }
  29. func TestCreateBucket(t *testing.T) {
  30. input := &s3.CreateBucketInput{
  31. Bucket: aws.String("theBucket"),
  32. }
  33. result, err := svc.CreateBucket(input)
  34. if err != nil {
  35. if aerr, ok := err.(awserr.Error); ok {
  36. switch aerr.Code() {
  37. case s3.ErrCodeBucketAlreadyExists:
  38. fmt.Println(s3.ErrCodeBucketAlreadyExists, aerr.Error())
  39. case s3.ErrCodeBucketAlreadyOwnedByYou:
  40. fmt.Println(s3.ErrCodeBucketAlreadyOwnedByYou, aerr.Error())
  41. default:
  42. fmt.Println(aerr.Error())
  43. }
  44. } else {
  45. // Print the error, cast err to awserr.Error to get the Code and
  46. // Message from an error.
  47. fmt.Println(err.Error())
  48. }
  49. return
  50. }
  51. fmt.Println(result)
  52. }
  53. func TestListBuckets(t *testing.T) {
  54. input := &s3.PutObjectInput{
  55. ACL: aws.String("authenticated-read"),
  56. Body: aws.ReadSeekCloser(strings.NewReader("filetoupload")),
  57. Bucket: aws.String("theBucket"),
  58. Key: aws.String("exampleobject"),
  59. }
  60. result, err := svc.PutObject(input)
  61. if err != nil {
  62. if aerr, ok := err.(awserr.Error); ok {
  63. switch aerr.Code() {
  64. default:
  65. fmt.Println(aerr.Error())
  66. }
  67. } else {
  68. // Print the error, cast err to awserr.Error to get the Code and
  69. // Message from an error.
  70. fmt.Println(err.Error())
  71. }
  72. return
  73. }
  74. fmt.Println(result)
  75. }
  76. func TestPutObject(t *testing.T) {
  77. result, err := svc.ListBuckets(nil)
  78. if err != nil {
  79. exitErrorf("Unable to list buckets, %v", err)
  80. }
  81. fmt.Println("Buckets:")
  82. for _, b := range result.Buckets {
  83. fmt.Printf("* %s created on %s\n",
  84. aws.StringValue(b.Name), aws.TimeValue(b.CreationDate))
  85. }
  86. }
  87. func exitErrorf(msg string, args ...interface{}) {
  88. fmt.Fprintf(os.Stderr, msg+"\n", args...)
  89. os.Exit(1)
  90. }