80 lines
2.6 KiB
Go
80 lines
2.6 KiB
Go
package outboundimage
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
|
|
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
|
|
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
|
|
)
|
|
|
|
type AliyunOSSStore struct {
|
|
client *oss.Client
|
|
bucket string
|
|
}
|
|
|
|
func NewAliyunOSSStore(endpoint, region, accessKeyID, accessKeySecret, bucket string) (*AliyunOSSStore, error) {
|
|
endpoint = strings.TrimSpace(endpoint)
|
|
region = strings.TrimSpace(region)
|
|
accessKeyID = strings.TrimSpace(accessKeyID)
|
|
accessKeySecret = strings.TrimSpace(accessKeySecret)
|
|
bucket = strings.TrimSpace(bucket)
|
|
if endpoint == "" || region == "" || accessKeyID == "" || accessKeySecret == "" || bucket == "" {
|
|
return nil, errors.New("outbound image: OSS endpoint, region, credentials, and bucket are required")
|
|
}
|
|
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, "")
|
|
config := oss.LoadDefaultConfig().
|
|
WithCredentialsProvider(provider).
|
|
WithRegion(region).
|
|
WithEndpoint(endpoint)
|
|
return &AliyunOSSStore{client: oss.NewClient(config), bucket: bucket}, nil
|
|
}
|
|
|
|
func (s *AliyunOSSStore) Put(ctx context.Context, key string, data []byte, contentType string) error {
|
|
if s == nil || s.client == nil || strings.TrimSpace(key) == "" || len(data) == 0 {
|
|
return errors.New("outbound image: invalid OSS put request")
|
|
}
|
|
_, err := s.client.PutObject(ctx, &oss.PutObjectRequest{
|
|
Bucket: oss.Ptr(s.bucket),
|
|
Key: oss.Ptr(key),
|
|
Body: bytes.NewReader(data),
|
|
ContentType: oss.Ptr(contentType),
|
|
})
|
|
if err != nil {
|
|
return errors.New("outbound image: OSS put failed")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *AliyunOSSStore) Get(ctx context.Context, key string, maxBytes int64) ([]byte, string, error) {
|
|
if s == nil || s.client == nil || strings.TrimSpace(key) == "" || maxBytes <= 0 {
|
|
return nil, "", errors.New("outbound image: invalid OSS get request")
|
|
}
|
|
result, err := s.client.GetObject(ctx, &oss.GetObjectRequest{
|
|
Bucket: oss.Ptr(s.bucket),
|
|
Key: oss.Ptr(key),
|
|
})
|
|
if err != nil {
|
|
return nil, "", errors.New("outbound image: OSS get failed")
|
|
}
|
|
defer result.Body.Close()
|
|
if result.ContentLength > maxBytes {
|
|
return nil, "", errors.New("outbound image: OSS object exceeds size limit")
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(result.Body, maxBytes+1))
|
|
if err != nil {
|
|
return nil, "", errors.New("outbound image: OSS read failed")
|
|
}
|
|
if int64(len(data)) > maxBytes {
|
|
return nil, "", errors.New("outbound image: OSS object exceeds size limit")
|
|
}
|
|
contentType := ""
|
|
if result.ContentType != nil {
|
|
contentType = strings.TrimSpace(*result.ContentType)
|
|
}
|
|
return data, contentType, nil
|
|
}
|