GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.1 KiB

  1. package store
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. minio "github.com/minio/minio-go"
  8. )
  9. var spaceBucket string
  10. var spaceURLRoot string
  11. var spaceRoot string
  12. var spaceClient *minio.Client
  13. var spaceMaxSize int64
  14. // ConnectSpace connects to a S3 space.
  15. func ConnectSpace(host, accessKey, secretKey, bucket string, maxSize int64, rootDirectory string) error {
  16. client, err := minio.New(host, accessKey, secretKey, true)
  17. if err != nil {
  18. return err
  19. }
  20. exists, err := client.BucketExists(bucket)
  21. if err != nil {
  22. return err
  23. }
  24. if !exists {
  25. return errors.New("Bucket not found")
  26. }
  27. spaceClient = client
  28. spaceBucket = bucket
  29. spaceURLRoot = fmt.Sprintf("https://%s.%s/%s/", bucket, host, rootDirectory)
  30. spaceMaxSize = maxSize
  31. spaceRoot = rootDirectory
  32. return nil
  33. }
  34. // UploadFile uploads the file to the space. This does not do any checks on it, so the endpoints should
  35. // ensure that's all okay.
  36. func UploadFile(ctx context.Context, folder string, name string, mimeType string, reader io.Reader, size int64) (string, error) {
  37. path := folder + "/" + name
  38. if size > spaceMaxSize {
  39. return "", errors.New("File is too big")
  40. }
  41. _, err := spaceClient.PutObjectWithContext(ctx, spaceBucket, spaceRoot+"/"+path, reader, size, minio.PutObjectOptions{
  42. ContentType: mimeType,
  43. UserMetadata: map[string]string{
  44. "x-amz-acl": "public-read",
  45. },
  46. })
  47. if err != nil {
  48. return "", err
  49. }
  50. _, err = spaceClient.StatObject(spaceBucket, spaceRoot+"/"+path, minio.StatObjectOptions{})
  51. if err != nil {
  52. return "", err
  53. }
  54. return path, nil
  55. }
  56. // RemoveFile removes a file from the space
  57. func RemoveFile(folder string, name string) error {
  58. path := folder + "/" + name
  59. return spaceClient.RemoveObject(spaceBucket, spaceRoot+"/"+path)
  60. }
  61. // DownloadFile opens a file for download, using the same path format as the UploadFile function. Remember to Close it!
  62. func DownloadFile(ctx context.Context, path string) (io.ReadCloser, error) {
  63. return spaceClient.GetObjectWithContext(ctx, spaceBucket, spaceRoot+"/"+path, minio.GetObjectOptions{})
  64. }
  65. // URLFromPath gets the URL from the path returned by UploadFile
  66. func URLFromPath(path string) string {
  67. return spaceURLRoot + path
  68. }