Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. package s3mock
  2.  
  3. import (
  4. "bytes"
  5. "errors"
  6. awsS3 "github.com/aws/aws-sdk-go/service/s3"
  7. "github.com/aws/aws-sdk-go/service/s3/s3iface"
  8. "io"
  9. "io/ioutil"
  10. "strings"
  11. )
  12.  
  13. type byteReadCloser struct {
  14. *bytes.Reader
  15. }
  16.  
  17. func (b *byteReadCloser) Close() error {
  18. return nil
  19. }
  20.  
  21. type fakeS3 struct {
  22. s3iface.S3API
  23. store map[string][]byte
  24. }
  25.  
  26. func newFakeS3() *fakeS3 {
  27. var fakeS3 fakeS3
  28. fakeS3.store = map[string][]byte{}
  29. return &fakeS3
  30. }
  31.  
  32. func (f *fakeS3) PutObject(iput *awsS3.PutObjectInput) (*awsS3.PutObjectOutput, error) {
  33. _, err := iput.Body.Seek(0, io.SeekStart)
  34. if err != nil {
  35. return nil, err
  36. }
  37.  
  38. b, err := ioutil.ReadAll(iput.Body)
  39. if err != nil {
  40. return nil, err
  41. }
  42.  
  43. f.store[*iput.Key] = b
  44.  
  45. return &awsS3.PutObjectOutput{}, nil
  46. }
  47.  
  48. func (f *fakeS3) ListObjectsV2(iput *awsS3.ListObjectsV2Input) (*awsS3.ListObjectsV2Output, error) {
  49. var (
  50. objs []*awsS3.Object
  51. isTruncated bool
  52. )
  53.  
  54. prefix := iput.Prefix
  55.  
  56. num := 0
  57. for key, _ := range f.store {
  58. if strings.Index(key, *prefix) == 0 {
  59. objKey := key
  60. objs = append(objs, &awsS3.Object{
  61. Key: &objKey,
  62. })
  63. }
  64.  
  65. num += 1
  66. if num >= 1000 {
  67. isTruncated = true
  68. break
  69. }
  70. }
  71.  
  72. return &awsS3.ListObjectsV2Output{
  73. Contents: objs,
  74. IsTruncated: &isTruncated,
  75. NextContinuationToken: nil,
  76. ContinuationToken: nil,
  77. }, nil
  78. }
  79.  
  80. func (f *fakeS3) GetObject(iput *awsS3.GetObjectInput) (*awsS3.GetObjectOutput, error) {
  81. if iput.Key == nil {
  82. return nil, errors.New("key not supplied")
  83. }
  84.  
  85. key := *iput.Key
  86.  
  87. b, ok := f.store[key]
  88.  
  89. if !ok {
  90. return nil, errors.New("item not found")
  91. }
  92.  
  93. return &awsS3.GetObjectOutput{
  94. Body: &byteReadCloser{bytes.NewReader(b)},
  95. }, nil
  96.  
  97. }
  98.  
  99. func getTestStore() s3.Store {
  100. var store s3.Store
  101. store.Bucket = "test-bucket"
  102. store.S3 = newFakeS3()
  103. return store
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement