This will probably just morph further into a "bucket" module for uploading, listing, deleting, etc.
93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package uploader
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
func UploadFile(bucketName, endpoint, fileName string) error {
|
|
|
|
ctx := context.Background()
|
|
accessKeyID, secretAccessKey, err := getCredentials()
|
|
if err != nil {
|
|
return (err)
|
|
}
|
|
client, err := createClient(accessKeyID, secretAccessKey, endpoint)
|
|
if err != nil {
|
|
return (err)
|
|
}
|
|
err = verifyBucket(client, ctx, bucketName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
absolutePath, basename, err := validateUploadFile(fileName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = client.FPutObject(ctx, bucketName, basename, absolutePath, minio.PutObjectOptions{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.Printf("upload of %s complete\n", basename)
|
|
return nil
|
|
}
|
|
|
|
func validateUploadFile(fileName string) (string, string, error) {
|
|
file, err := os.Stat(fileName)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
if file.IsDir() {
|
|
return "", "", errors.New("upload of directories is not supported")
|
|
}
|
|
|
|
return fileName, file.Name(), nil
|
|
}
|
|
|
|
func verifyBucket(client *minio.Client, ctx context.Context, bucketName string) error {
|
|
exists, err := client.BucketExists(ctx, bucketName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !exists {
|
|
return errors.New(fmt.Sprintf("bucket %s does not exist\n", bucketName))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func createClient(accessKeyID, secretAccessKey, endpoint string) (*minio.Client, error) {
|
|
// Initialize minio client object.
|
|
minioClient, err := minio.New(endpoint, &minio.Options{
|
|
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
|
Secure: true,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return minioClient, nil
|
|
}
|
|
|
|
func getCredentials() (string, string, error) {
|
|
// get credentials from env vars
|
|
keyName := os.Getenv("KEY_ID")
|
|
if keyName == "" {
|
|
return "", "", errors.New("missing or empty KEY_ID")
|
|
}
|
|
applicationKey := os.Getenv("APPLICATION_KEY")
|
|
if applicationKey == "" {
|
|
return "", "", errors.New("missing or empty APPLICATION_KEY")
|
|
}
|
|
return keyName, applicationKey, nil
|
|
}
|