|
|
package store
import ( "context" "errors" "fmt" "io"
minio "github.com/minio/minio-go" )
var spaceBucket string var spaceURLRoot string var spaceRoot string var spaceClient *minio.Client var spaceMaxSize int64
// ConnectSpace connects to a S3 space.
func ConnectSpace(host, accessKey, secretKey, bucket string, maxSize int64, rootDirectory string) error { client, err := minio.New(host, accessKey, secretKey, true) if err != nil { return err }
exists, err := client.BucketExists(bucket) if err != nil { return err }
if !exists { return errors.New("Bucket not found") }
spaceClient = client spaceBucket = bucket spaceURLRoot = fmt.Sprintf("https://%s.%s/%s/", bucket, host, rootDirectory) spaceMaxSize = maxSize spaceRoot = rootDirectory
return nil }
// UploadFile uploads the file to the space. This does not do any checks on it, so the endpoints should
// ensure that's all okay.
func UploadFile(ctx context.Context, folder string, name string, mimeType string, reader io.Reader, size int64) (string, error) { if spaceClient == nil { return "", errors.New("This functionality is not enabled") }
path := folder + "/" + name
if size > spaceMaxSize { return "", errors.New("File is too big") }
_, err := spaceClient.PutObjectWithContext(ctx, spaceBucket, spaceRoot+"/"+path, reader, size, minio.PutObjectOptions{ ContentType: mimeType, UserMetadata: map[string]string{ "x-amz-acl": "public-read", }, }) if err != nil { return "", err }
_, err = spaceClient.StatObject(spaceBucket, spaceRoot+"/"+path, minio.StatObjectOptions{}) if err != nil { return "", err }
return path, nil }
// RemoveFile removes a file from the space
func RemoveFile(folder string, name string) error { if spaceClient == nil { return errors.New("This functionality is not enabled") }
path := folder + "/" + name
return spaceClient.RemoveObject(spaceBucket, spaceRoot+"/"+path) }
// DownloadFile opens a file for download, using the same path format as the UploadFile function. Remember to Close it!
func DownloadFile(ctx context.Context, path string) (io.ReadCloser, error) { if spaceClient == nil { return nil, errors.New("This functionality is not enabled") }
return spaceClient.GetObjectWithContext(ctx, spaceBucket, spaceRoot+"/"+path, minio.GetObjectOptions{}) }
// URLFromPath gets the URL from the path returned by UploadFile
func URLFromPath(path string) string { return spaceURLRoot + path }
|