file_uploader.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package awsuploader
  2. import (
  3. "context"
  4. "os"
  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. )
  10. //FileUploader aws compliant bucket upload
  11. type FileUploader struct {
  12. storage *s3.S3
  13. bucketName string
  14. clientID string
  15. secretID string
  16. }
  17. // NewFileUploader creates a new S3 compliant bucket uploader
  18. func NewFileUploader(bucketName, region, accessKeyID, secretID, token, s3Host string) (*FileUploader, error) {
  19. sess, err := session.NewSession(&aws.Config{
  20. Region: aws.String(region),
  21. Credentials: credentials.NewStaticCredentials(accessKeyID, secretID, token),
  22. })
  23. if err != nil {
  24. return nil, err
  25. }
  26. var storage *s3.S3
  27. if s3Host != "" {
  28. storage = s3.New(sess, &aws.Config{Endpoint: aws.String(s3Host)})
  29. } else {
  30. storage = s3.New(sess)
  31. }
  32. return &FileUploader{
  33. storage: storage,
  34. bucketName: bucketName,
  35. }, nil
  36. }
  37. // Upload a file to the bucket
  38. func (u *FileUploader) Upload(filepath string) error {
  39. info, err := os.Stat(filepath)
  40. if err != nil {
  41. return err
  42. }
  43. file, err := os.Open(filepath)
  44. if err != nil {
  45. return err
  46. }
  47. defer file.Close()
  48. _, serr := u.storage.PutObjectWithContext(context.Background(), &s3.PutObjectInput{
  49. Bucket: aws.String(u.bucketName),
  50. Key: aws.String(info.Name()),
  51. Body: file,
  52. })
  53. return serr
  54. }