2021-07-21 15:35:22 +02:00
|
|
|
package s3
|
|
|
|
|
|
|
|
import (
|
2021-07-22 15:01:48 +02:00
|
|
|
"context"
|
|
|
|
"errors"
|
2021-07-21 15:35:22 +02:00
|
|
|
"net/url"
|
|
|
|
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
|
|
)
|
|
|
|
|
2021-07-22 15:01:48 +02:00
|
|
|
// Error Messages during connect
|
|
|
|
var (
|
|
|
|
ErrNoPassword = errors.New("no secret access key found")
|
|
|
|
)
|
|
|
|
|
2021-07-21 15:35:22 +02:00
|
|
|
// Connect try to use a path to setup a connection to s3 server
|
2021-07-22 15:01:48 +02:00
|
|
|
func Connect(path string) (*minio.Client, string, error) {
|
|
|
|
u, err := url.Parse(path)
|
2021-07-21 15:35:22 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, "", err
|
|
|
|
}
|
|
|
|
|
2021-07-22 15:01:48 +02:00
|
|
|
tls := u.Scheme[len(u.Scheme)-1] == 's'
|
|
|
|
accessKeyID := u.User.Username()
|
|
|
|
secretAccessKey, ok := u.User.Password()
|
|
|
|
if !ok {
|
|
|
|
return nil, "", ErrNoPassword
|
2021-07-21 15:35:22 +02:00
|
|
|
}
|
2021-07-22 15:01:48 +02:00
|
|
|
query := u.Query()
|
|
|
|
bucketName := query.Get("bucket")
|
|
|
|
location := query.Get("location")
|
|
|
|
|
|
|
|
u.User = nil
|
|
|
|
u.RawQuery = ""
|
|
|
|
|
|
|
|
ctx := context.Background()
|
2021-07-21 15:35:22 +02:00
|
|
|
|
|
|
|
// Initialize minio client object.
|
2021-07-22 15:01:48 +02:00
|
|
|
minioClient, err := minio.New(u.String(), &minio.Options{
|
|
|
|
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
|
|
|
Secure: tls,
|
2021-07-21 15:35:22 +02:00
|
|
|
})
|
2021-07-22 15:01:48 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// create and check for bucket
|
|
|
|
err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
|
|
|
|
if err != nil {
|
|
|
|
if exists, err := minioClient.BucketExists(ctx, bucketName); err != nil || !exists {
|
|
|
|
return nil, "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return minioClient, bucketName, err
|
2021-07-21 15:35:22 +02:00
|
|
|
}
|