minio.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package storage
  2. import (
  3. "context"
  4. "io"
  5. "git.linuxforward.com/byom/byom-golang-lib/pkg/errors"
  6. "github.com/minio/minio-go/v7"
  7. "github.com/minio/minio-go/v7/pkg/credentials"
  8. )
  9. type MinioConfig struct {
  10. Endpoint string
  11. AccessKeyID string
  12. SecretAccessKey string
  13. UseSSL bool
  14. BucketName string
  15. }
  16. type MinioClient struct {
  17. client *minio.Client
  18. bucketName string
  19. }
  20. func NewMinioClient(config MinioConfig) (*MinioClient, error) {
  21. if config.Endpoint == "" {
  22. return nil, errors.NewStorageError("initialize", "", errors.ErrInvalidInput)
  23. }
  24. client, err := minio.New(config.Endpoint, &minio.Options{
  25. Creds: credentials.NewStaticV4(config.AccessKeyID, config.SecretAccessKey, ""),
  26. Secure: config.UseSSL,
  27. })
  28. if err != nil {
  29. return nil, errors.NewStorageError("create_client", "", err)
  30. }
  31. // Ensure bucket exists
  32. ctx := context.Background()
  33. exists, err := client.BucketExists(ctx, config.BucketName)
  34. if err != nil {
  35. return nil, errors.NewStorageError("check_bucket", config.BucketName, err)
  36. }
  37. if !exists {
  38. err = client.MakeBucket(ctx, config.BucketName, minio.MakeBucketOptions{})
  39. if err != nil {
  40. return nil, errors.NewStorageError("create_bucket", config.BucketName, err)
  41. }
  42. }
  43. return &MinioClient{
  44. client: client,
  45. bucketName: config.BucketName,
  46. }, nil
  47. }
  48. // Client returns the underlying Minio client
  49. func (m *MinioClient) Client() *minio.Client {
  50. return m.client
  51. }
  52. // BucketName returns the name of the bucket
  53. func (m *MinioClient) BucketName() string {
  54. return m.bucketName
  55. }
  56. // PutObject is a helper method to upload an object to the bucket
  57. func (m *MinioClient) PutObject(ctx context.Context, objectName string, reader io.Reader, objectSize int64, opts minio.PutObjectOptions) (info minio.UploadInfo, err error) {
  58. return m.client.PutObject(ctx, m.bucketName, objectName, reader, objectSize, opts)
  59. }
  60. // GetObject is a helper method to download an object from the bucket
  61. func (m *MinioClient) GetObject(ctx context.Context, objectName string, opts minio.GetObjectOptions) (*minio.Object, error) {
  62. return m.client.GetObject(ctx, m.bucketName, objectName, opts)
  63. }