s3_sessions.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package s3_backend
  2. import (
  3. "fmt"
  4. "sync"
  5. "github.com/aws/aws-sdk-go/aws"
  6. "github.com/aws/aws-sdk-go/aws/credentials"
  7. "github.com/aws/aws-sdk-go/aws/session"
  8. "github.com/aws/aws-sdk-go/service/s3"
  9. "github.com/aws/aws-sdk-go/service/s3/s3iface"
  10. )
  11. var (
  12. s3Sessions = make(map[string]s3iface.S3API)
  13. sessionsLock sync.RWMutex
  14. )
  15. func getSession(region string) (s3iface.S3API, bool) {
  16. sessionsLock.RLock()
  17. defer sessionsLock.RUnlock()
  18. sess, found := s3Sessions[region]
  19. return sess, found
  20. }
  21. func createSession(awsAccessKeyId, awsSecretAccessKey, region, endpoint string) (s3iface.S3API, error) {
  22. sessionsLock.Lock()
  23. defer sessionsLock.Unlock()
  24. if t, found := s3Sessions[region]; found {
  25. return t, nil
  26. }
  27. config := &aws.Config{
  28. Region: aws.String(region),
  29. Endpoint: aws.String(endpoint),
  30. S3ForcePathStyle: aws.Bool(true),
  31. }
  32. if awsAccessKeyId != "" && awsSecretAccessKey != "" {
  33. config.Credentials = credentials.NewStaticCredentials(awsAccessKeyId, awsSecretAccessKey, "")
  34. }
  35. sess, err := session.NewSession(config)
  36. if err != nil {
  37. return nil, fmt.Errorf("create aws session in region %s: %v", region, err)
  38. }
  39. t := s3.New(sess)
  40. s3Sessions[region] = t
  41. return t, nil
  42. }
  43. func deleteFromS3(sess s3iface.S3API, sourceBucket string, sourceKey string) (err error) {
  44. _, err = sess.DeleteObject(&s3.DeleteObjectInput{
  45. Bucket: aws.String(sourceBucket),
  46. Key: aws.String(sourceKey),
  47. })
  48. return err
  49. }