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 "" } return fmt.Sprintf("%s:%s%s", r.cfg.GetPublicURL(), r.cfg.GetBucketName(), fileName) }