s3.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package s3
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "github.com/aws/aws-sdk-go-v2/aws"
  7. s3config "github.com/aws/aws-sdk-go-v2/config"
  8. "github.com/aws/aws-sdk-go-v2/credentials"
  9. "github.com/aws/aws-sdk-go-v2/feature/s3/manager"
  10. awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
  11. "github.com/aws/aws-sdk-go-v2/service/s3/types"
  12. )
  13. type Config struct {
  14. AccessKey string
  15. SecretKey string
  16. Bucket string
  17. EndPoint string
  18. Region string
  19. URLPrefix string
  20. }
  21. type Client struct {
  22. Client *awss3.Client
  23. Config *Config
  24. }
  25. func NewClient(ctx context.Context, config *Config) (*Client, error) {
  26. resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
  27. return aws.Endpoint{
  28. URL: config.EndPoint,
  29. SigningRegion: config.Region,
  30. }, nil
  31. })
  32. awsConfig, err := s3config.LoadDefaultConfig(ctx,
  33. s3config.WithEndpointResolverWithOptions(resolver),
  34. s3config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(config.AccessKey, config.SecretKey, "")),
  35. )
  36. if err != nil {
  37. return nil, err
  38. }
  39. client := awss3.NewFromConfig(awsConfig)
  40. return &Client{
  41. Client: client,
  42. Config: config,
  43. }, nil
  44. }
  45. func (client *Client) UploadFile(ctx context.Context, filename string, fileType string, src io.Reader) (string, error) {
  46. uploader := manager.NewUploader(client.Client)
  47. uploadOutput, err := uploader.Upload(ctx, &awss3.PutObjectInput{
  48. Bucket: aws.String(client.Config.Bucket),
  49. Key: aws.String(filename),
  50. Body: src,
  51. ContentType: aws.String(fileType),
  52. ACL: types.ObjectCannedACL(*aws.String("public-read")),
  53. })
  54. if err != nil {
  55. return "", err
  56. }
  57. link := uploadOutput.Location
  58. // If url prefix is set, use it as the file link.
  59. if client.Config.URLPrefix != "" {
  60. link = fmt.Sprintf("%s/%s", client.Config.URLPrefix, filename)
  61. }
  62. if link == "" {
  63. return "", fmt.Errorf("failed to get file link")
  64. }
  65. return link, nil
  66. }