apskel-pos-backend/internal/client/s3_flie_client.go

68 lines
1.5 KiB
Go
Raw Normal View History

2025-07-18 20:10:29 +07:00
package client
2023-10-08 15:59:42 +07:00
import (
"bytes"
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
2025-07-18 20:10:29 +07:00
type FileConfig interface {
2023-10-08 15:59:42 +07:00
GetAccessKeyID() string
GetAccessKeySecret() string
GetEndpoint() string
GetBucketName() string
GetHostURL() string
}
const _awsRegion = "us-east-1"
const _s3ACL = "public-read"
2025-07-18 20:10:29 +07:00
type S3FileClientImpl struct {
2023-10-08 15:59:42 +07:00
s3 *s3.S3
2025-07-18 20:10:29 +07:00
cfg FileConfig
2023-10-08 15:59:42 +07:00
}
2025-07-18 20:10:29 +07:00
func NewFileClient(fileCfg FileConfig) *S3FileClientImpl {
2023-10-08 15:59:42 +07:00
sess, err := session.NewSession(&aws.Config{
S3ForcePathStyle: aws.Bool(true),
2025-07-18 20:10:29 +07:00
Endpoint: aws.String(fileCfg.GetEndpoint()),
2023-10-08 15:59:42 +07:00
Region: aws.String(_awsRegion),
2025-07-18 20:10:29 +07:00
Credentials: credentials.NewStaticCredentials(fileCfg.GetAccessKeyID(), fileCfg.GetAccessKeySecret(), ""),
2023-10-08 15:59:42 +07:00
})
if err != nil {
fmt.Println("Failed to create AWS session:", err)
return nil
}
2025-07-18 20:10:29 +07:00
return &S3FileClientImpl{
2023-10-08 15:59:42 +07:00
s3: s3.New(sess),
2025-07-18 20:10:29 +07:00
cfg: fileCfg,
2023-10-08 15:59:42 +07:00
}
}
2025-07-18 20:10:29 +07:00
func (r *S3FileClientImpl) UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error) {
2023-10-08 15:59:42 +07:00
reader := bytes.NewReader(fileContent)
_, err = r.s3.PutObject(&s3.PutObjectInput{
Bucket: aws.String(r.cfg.GetBucketName()),
Key: aws.String(fileName),
Body: reader,
ACL: aws.String(_s3ACL),
})
return r.GetPublicURL(fileName), err
}
2025-07-18 20:10:29 +07:00
func (r *S3FileClientImpl) GetPublicURL(fileName string) string {
2023-10-08 15:59:42 +07:00
if fileName == "" {
return ""
}
2025-03-08 00:35:23 +07:00
return fmt.Sprintf("%s%s%s", r.cfg.GetHostURL(), r.cfg.GetBucketName(), fileName)
2023-10-08 15:59:42 +07:00
}