2025-03-03 18:59:25 +07:00
|
|
|
package oss
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"legalgo-BE-go/config"
|
|
|
|
|
|
|
|
|
|
"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"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type OSSConfig interface {
|
|
|
|
|
GetAccessKeyID() string
|
|
|
|
|
GetAccessKeySecret() string
|
|
|
|
|
GetEndpoint() string
|
|
|
|
|
GetBucketName() string
|
|
|
|
|
GetHostURL() string
|
|
|
|
|
GetPublicURL() string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const _awsRegion = "us-east-1"
|
|
|
|
|
const _s3ACL = "public-read"
|
|
|
|
|
|
|
|
|
|
type OssRepositoryImpl struct {
|
|
|
|
|
s3 *s3.S3
|
|
|
|
|
cfg OSSConfig
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func New(cfg *config.Config) OSSRepository {
|
|
|
|
|
ossCfg := cfg.OSSConfig
|
|
|
|
|
sess, err := session.NewSession(&aws.Config{
|
|
|
|
|
S3ForcePathStyle: aws.Bool(true),
|
|
|
|
|
Endpoint: aws.String(ossCfg.GetEndpoint()),
|
|
|
|
|
Region: aws.String(_awsRegion),
|
|
|
|
|
Credentials: credentials.NewStaticCredentials(ossCfg.GetAccessKeyID(), ossCfg.GetAccessKeySecret(), ""),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
fmt.Println("Failed to create AWS session:", err)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &OssRepositoryImpl{
|
|
|
|
|
s3: s3.New(sess),
|
|
|
|
|
cfg: ossCfg,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *OssRepositoryImpl) UploadFile(ctx context.Context, fileName string, fileContent []byte) (fileUrl string, err error) {
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *OssRepositoryImpl) GetPublicURL(fileName string) string {
|
|
|
|
|
if fileName == "" {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
2025-04-23 13:50:41 +08:00
|
|
|
return fmt.Sprintf("%s/%s%s", r.cfg.GetPublicURL(), r.cfg.GetBucketName(), fileName)
|
2025-03-03 18:59:25 +07:00
|
|
|
}
|
2025-03-09 00:47:24 +08:00
|
|
|
|
|
|
|
|
func (r *OssRepositoryImpl) DeleteObject(ctx context.Context, fileName string) error {
|
|
|
|
|
if fileName == "" {
|
|
|
|
|
return fmt.Errorf("file name is not provided")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, err := r.s3.DeleteObject(&s3.DeleteObjectInput{
|
|
|
|
|
Key: aws.String(fileName),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("failed to delete object %s from bucket: %v", fileName, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|