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) { 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, path, minio.StatObjectOptions{}) if err != nil { return "", err } return path, nil } // 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) { 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 }