s3_sessions.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 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. }
  30. if awsAccessKeyId != "" && awsSecretAccessKey != "" {
  31. config.Credentials = credentials.NewStaticCredentials(awsAccessKeyId, awsSecretAccessKey, "")
  32. }
  33. sess, err := session.NewSession(config)
  34. if err != nil {
  35. return nil, fmt.Errorf("create aws session in region %s: %v", region, err)
  36. }
  37. t := s3.New(sess)
  38. s3Sessions[region] = t
  39. return t, nil
  40. }