memos/plugin/storage/s3/s3.go

74 lines
1.8 KiB
Go
Raw Normal View History

package s3
import (
"context"
"fmt"
"io"
"github.com/aws/aws-sdk-go-v2/aws"
2023-02-23 19:02:51 +03:00
s3config "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
)
2023-02-23 19:02:51 +03:00
type Config struct {
AccessKey string
SecretKey string
Bucket string
EndPoint string
Region string
URLPrefix string
}
type Client struct {
2023-02-23 19:02:51 +03:00
Client *awss3.Client
Config *Config
}
2023-02-23 19:02:51 +03:00
func NewClient(ctx context.Context, config *Config) (*Client, error) {
resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
2023-02-23 19:02:51 +03:00
URL: config.EndPoint,
SigningRegion: config.Region,
}, nil
})
2023-02-23 19:02:51 +03:00
cfg, err := s3config.LoadDefaultConfig(ctx,
s3config.WithEndpointResolverWithOptions(resolver),
s3config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(config.AccessKey, config.SecretKey, "")),
)
if err != nil {
return nil, err
}
client := awss3.NewFromConfig(cfg)
return &Client{
2023-02-23 19:02:51 +03:00
Client: client,
Config: config,
}, nil
}
2023-02-23 19:02:51 +03:00
func (client *Client) UploadFile(ctx context.Context, filename string, fileType string, src io.Reader) (string, error) {
uploader := manager.NewUploader(client.Client)
resp, err := uploader.Upload(ctx, &awss3.PutObjectInput{
2023-02-23 19:02:51 +03:00
Bucket: aws.String(client.Config.Bucket),
Key: aws.String(filename),
Body: src,
ContentType: aws.String(fileType),
ACL: types.ObjectCannedACL(*aws.String("public-read")),
})
if err != nil {
return "", err
}
var link string
2023-02-23 19:02:51 +03:00
if client.Config.URLPrefix == "" {
link = resp.Location
} else {
2023-02-23 19:02:51 +03:00
link = fmt.Sprintf("%s/%s", client.Config.URLPrefix, filename)
}
return link, nil
}