You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

minio.go 1.9 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package storage
  5. import (
  6. "io"
  7. "path"
  8. "strings"
  9. "github.com/minio/minio-go"
  10. )
  11. var (
  12. _ ObjectStorage = &MinioStorage{}
  13. )
  14. // MinioStorage returns a minio bucket storage
  15. type MinioStorage struct {
  16. client *minio.Client
  17. bucket string
  18. basePath string
  19. }
  20. // NewMinioStorage returns a minio storage
  21. func NewMinioStorage(endpoint, accessKeyID, secretAccessKey, bucket, location, basePath string, useSSL bool) (*MinioStorage, error) {
  22. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  23. if err != nil {
  24. return nil, err
  25. }
  26. if err := minioClient.MakeBucket(bucket, location); err != nil {
  27. // Check to see if we already own this bucket (which happens if you run this twice)
  28. exists, errBucketExists := minioClient.BucketExists(bucket)
  29. if !exists || errBucketExists != nil {
  30. return nil, err
  31. }
  32. }
  33. return &MinioStorage{
  34. client: minioClient,
  35. bucket: bucket,
  36. basePath: basePath,
  37. }, nil
  38. }
  39. func (m *MinioStorage) buildMinioPath(p string) string {
  40. return strings.TrimPrefix(path.Join(m.basePath, p), "/")
  41. }
  42. // Open open a file
  43. func (m *MinioStorage) Open(path string) (io.ReadCloser, error) {
  44. var opts = minio.GetObjectOptions{}
  45. object, err := m.client.GetObject(m.bucket, m.buildMinioPath(path), opts)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return object, nil
  50. }
  51. // Save save a file to minio
  52. func (m *MinioStorage) Save(path string, r io.Reader) (int64, error) {
  53. return m.client.PutObject(m.bucket, m.buildMinioPath(path), r, -1, minio.PutObjectOptions{ContentType: "application/octet-stream"})
  54. }
  55. // Delete delete a file
  56. func (m *MinioStorage) Delete(path string) error {
  57. return m.client.RemoveObject(m.bucket, m.buildMinioPath(path))
  58. }