MinIO 是一个基于 Apache License v2.0 开源协议的对象存储服务,与 Amazon S3 云存储服务兼容,适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器 / 虚拟机镜像等。在 Go 语言中,可以使用 MinIO 官方提供的 Go 客户端库与 MinIO 服务进行交互。以下是关于在 Go 语言中使用 MinIO 的详细代码如下介绍:
Go
package minio
import (
"bytes"
"context"
"fmt"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"io"
"log"
"net/url"
"os"
"path"
"time"
)
type Minio struct {
client *minio.Client // 连接对象
bucketName string // 桶名称
}
// NewMinio ...
// endpoint 连接地址;accessKey 访问key;secret 访问密钥;bucketName 桶名称
func NewMinio(endpoint, accessKey, secret, bucketName string) Minio {
// Initialize minio client object.
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secret, ""),
Secure: false,
})
if err != nil {
log.Fatal("文件服务连接失败;err=", err)
}
return Minio{
client: minioClient,
//logger: logger,
bucketName: bucketName,
}
}
// CreateBucket 创建桶
func (m Minio) CreateBucket(ctx context.Context) error {
err := m.client.MakeBucket(ctx, m.bucketName, minio.MakeBucketOptions{Region: "cn-north-1"})
if err != nil {
// 检查存储桶是否已存在,若已存在导致的错误则忽略
if exists, errExists := m.BucketExists(ctx, m.bucketName); errExists == nil && exists {
return nil
}
return fmt.Errorf("创建存储桶失败: %v", err)
}
//m.logger.Info("存储桶 %s 创建成功\n", m.bucketName)
return nil
}
// ListBuckets 查询桶列表
func (m Minio) ListBuckets(ctx context.Context) ([]minio.BucketInfo, error) {
buckets, err := m.client.ListBuckets(ctx)
if err != nil {
return nil, err
}
return buckets, nil
}
// BucketExists 检查桶是否存在
func (m Minio) BucketExists(ctx context.Context, bucketName string) (bool, error) {
found, err := m.client.BucketExists(ctx, bucketName)
if err != nil {
fmt.Println(err)
return false, err
}
return found, nil
}
// RemoveBucket 删除桶
func (m Minio) RemoveBucket(ctx context.Context) error {
isExist, err := m.BucketExists(ctx, m.bucketName)
if err != nil {
fmt.Printf("Check %s err:%s", m.bucketName, err.Error())
return err
}
if isExist {
fmt.Printf("%s exists! Start delete....\n", m.bucketName)
// 删除
if err = m.client.RemoveBucket(ctx, m.bucketName); err != nil {
fmt.Printf("Fail to remove %s:%s\n", m.bucketName, err.Error())
return err
}
fmt.Printf("Success to remove %s\n", m.bucketName)
} else {
fmt.Printf("%s not exists!\n", m.bucketName)
}
return nil
}
// UploadObject 上传文件对象
func (m Minio) UploadObject(ctx context.Context, objectName string, file *os.File) (*minio.UploadInfo, error) {
fileStat, err := file.Stat()
if err != nil {
return nil, err
}
fileType := "application/octet-stream"
switch path.Ext(objectName) {
case ".jpg", ".jpeg":
fileType = "image/jpeg"
case ".png":
fileType = "image/png"
case ".gif":
fileType = "image/gif"
case ".webp":
fileType = "image/webp"
case ".mp4":
fileType = "video/mp4"
case ".avi":
fileType = "video/avi"
case ".pdf":
fileType = "application/pdf"
case ".doc":
fileType = "application/msword"
}
// upload the file
uploadInfo, err := m.client.PutObject(
ctx,
m.bucketName,
objectName,
file,
fileStat.Size(),
minio.PutObjectOptions{ContentType: fileType})
return &uploadInfo, err
}
// ReadObject 获取文件对象
func (m Minio) ReadObject(ctx context.Context, objectName string) ([]byte, error) {
contentBuffer, err := m.client.GetObject(ctx, m.bucketName, objectName, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
// read the content from the buffer
contentBytes := new(bytes.Buffer)
if _, err = io.Copy(contentBytes, contentBuffer); err != nil {
return nil, err
}
return contentBytes.Bytes(), nil
}
// StateObjects 查询文件信息
func (m Minio) StateObjects(ctx context.Context, objectName string) (*minio.ObjectInfo, error) {
objInfo, err := m.client.StatObject(ctx, m.bucketName, objectName, minio.StatObjectOptions{})
if err != nil {
return nil, err
}
return &objInfo, err
}
// PresignedGetObject 创建预览地址
func (m Minio) PresignedGetObject(ctx context.Context, objectName string) (*url.URL, error) {
reqParams := make(url.Values)
// 若需要生成的链接直接下载文件的把下面的注释打开,需要预览的则不需要打开
//reqParams.Set("response-content-disposition", "attachment; filename="+path.Base(objectName))
// Generates a presigned url which expires in a day.
presignedURL, err := m.client.PresignedGetObject(ctx, m.bucketName, objectName, time.Second*24*60*60, reqParams)
if err != nil {
return nil, err
}
return presignedURL, err
}
// RemoveObject 删除文件对象
func (m Minio) RemoveObject(ctx context.Context, objectName string) error {
opts := minio.RemoveObjectOptions{}
err := m.client.RemoveObject(ctx, m.bucketName, objectName, opts)
if err != nil {
fmt.Println(err)
return err
}
return nil
}
官网API地址MinIO Go Client API Reference --- MinIO中文文档 | MinIO Linux中文文档