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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. location string
  19. basePath string
  20. }
  21. // NewMinioStorage returns a minio storage
  22. func NewMinioStorage(endpoint, accessKeyID, secretAccessKey, bucket, location, basePath string, useSSL bool) (*MinioStorage, error) {
  23. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  24. if err != nil {
  25. return nil, err
  26. }
  27. if err := minioClient.MakeBucket(bucket, location); err != nil {
  28. // Check to see if we already own this bucket (which happens if you run this twice)
  29. exists, errBucketExists := minioClient.BucketExists(bucket)
  30. if !exists || errBucketExists != nil {
  31. return nil, err
  32. }
  33. }
  34. return &MinioStorage{
  35. client: minioClient,
  36. bucket: bucket,
  37. basePath: basePath,
  38. }, nil
  39. }
  40. func (m *MinioStorage) buildMinioPath(p string) string {
  41. return strings.TrimPrefix(path.Join(m.basePath, p), "/")
  42. }
  43. // Open open a file
  44. func (m *MinioStorage) Open(path string) (io.ReadCloser, error) {
  45. var opts = minio.GetObjectOptions{}
  46. object, err := m.client.GetObject(m.bucket, m.buildMinioPath(path), opts)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return object, nil
  51. }
  52. // Save save a file to minio
  53. func (m *MinioStorage) Save(path string, r io.Reader) (int64, error) {
  54. return m.client.PutObject(m.bucket, m.buildMinioPath(path), r, -1, minio.PutObjectOptions{ContentType: "application/octet-stream"})
  55. }
  56. // Delete delete a file
  57. func (m *MinioStorage) Delete(path string) error {
  58. return m.client.RemoveObject(m.bucket, m.buildMinioPath(path))
  59. }