72 lines
1.8 KiB
Go
Raw Normal View History

package s3
import (
"context"
"io"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
2023-02-24 00:02:51 +08: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"
2024-01-29 23:15:47 +08:00
"github.com/pkg/errors"
)
const LinkLifetime = 24 * time.Hour
2023-02-24 00:02:51 +08:00
type Config struct {
2024-04-28 21:36:22 +08:00
AccessKeyID string
AcesssKeySecret string
Endpoint string
Region string
Bucket string
2023-02-24 00:02:51 +08:00
}
type Client struct {
2023-02-24 00:02:51 +08:00
Client *awss3.Client
Config *Config
}
2023-02-24 00:02:51 +08:00
func NewClient(ctx context.Context, config *Config) (*Client, error) {
resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...any) (aws.Endpoint, error) {
return aws.Endpoint{
2024-04-28 21:36:22 +08:00
URL: config.Endpoint,
}, nil
})
2024-04-28 21:36:22 +08:00
s3Config, err := s3config.LoadDefaultConfig(ctx,
2023-02-24 00:02:51 +08:00
s3config.WithEndpointResolverWithOptions(resolver),
2024-04-28 21:36:22 +08:00
s3config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(config.AccessKeyID, config.AcesssKeySecret, "")),
s3config.WithRegion(config.Region),
)
if err != nil {
2024-04-28 21:36:22 +08:00
return nil, errors.Wrap(err, "failed to load s3 config")
}
2024-04-28 21:36:22 +08:00
client := awss3.NewFromConfig(s3Config)
return &Client{
2023-02-24 00:02:51 +08:00
Client: client,
Config: config,
}, nil
}
2023-02-24 00:02:51 +08:00
func (client *Client) UploadFile(ctx context.Context, filename string, fileType string, src io.Reader) (string, error) {
uploader := manager.NewUploader(client.Client)
2023-11-24 21:55:09 +08:00
putInput := awss3.PutObjectInput{
2023-02-24 00:02:51 +08:00
Bucket: aws.String(client.Config.Bucket),
Key: aws.String(filename),
Body: src,
ContentType: aws.String(fileType),
}
2023-11-24 21:55:09 +08:00
uploadOutput, err := uploader.Upload(ctx, &putInput)
if err != nil {
return "", err
}
link := uploadOutput.Location
2023-03-04 20:06:32 +08:00
if link == "" {
2023-09-17 22:55:13 +08:00
return "", errors.New("failed to get file link")
2023-03-04 20:06:32 +08:00
}
return link, nil
}