minio.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 MinioClient struct {
  10. client *minio.Client
  11. bucketName string
  12. }
  13. func NewMinioClient(config *Config) (*MinioClient, error) {
  14. if config.Endpoint == "" {
  15. return nil, errors.NewStorageError("initialize", "", errors.ErrInvalidInput)
  16. }
  17. client, err := minio.New(config.Endpoint, &minio.Options{
  18. Creds: credentials.NewStaticV4(config.AccessKeyID, config.SecretAccessKey, ""),
  19. Secure: config.UseSSL,
  20. })
  21. if err != nil {
  22. return nil, errors.NewStorageError("create_client", "", err)
  23. }
  24. // Ensure bucket exists
  25. ctx := context.Background()
  26. exists, err := client.BucketExists(ctx, config.BucketName)
  27. if err != nil {
  28. return nil, errors.NewStorageError("check_bucket", config.BucketName, err)
  29. }
  30. if !exists {
  31. err = client.MakeBucket(ctx, config.BucketName, minio.MakeBucketOptions{})
  32. if err != nil {
  33. return nil, errors.NewStorageError("create_bucket", config.BucketName, err)
  34. }
  35. }
  36. return &MinioClient{
  37. client: client,
  38. bucketName: config.BucketName,
  39. }, nil
  40. }
  41. // Client returns the underlying Minio client
  42. func (m *MinioClient) Client() *minio.Client {
  43. return m.client
  44. }
  45. // BucketName returns the name of the bucket
  46. func (m *MinioClient) BucketName() string {
  47. return m.bucketName
  48. }
  49. // PutObject is a helper method to upload an object to the bucket
  50. func (m *MinioClient) PutObject(ctx context.Context, objectName string, reader io.Reader, objectSize int64, opts minio.PutObjectOptions) (info minio.UploadInfo, err error) {
  51. return m.client.PutObject(ctx, m.bucketName, objectName, reader, objectSize, opts)
  52. }
  53. // GetObject is a helper method to download an object from the bucket
  54. func (m *MinioClient) GetObject(ctx context.Context, objectName string, opts minio.GetObjectOptions) (*minio.Object, error) {
  55. return m.client.GetObject(ctx, m.bucketName, objectName, opts)
  56. }