当前位置: 首页 > news >正文

MinIO Go 客户端 API

MinIO 是一个基于 Apache License v2.0 开源协议的对象存储服务,与 Amazon S3 云存储服务兼容,适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器 / 虚拟机镜像等。在 Go 语言中,可以使用 MinIO 官方提供的 Go 客户端库与 MinIO 服务进行交互。以下是关于在 Go 语言中使用 MinIO 的详细代码如下介绍:

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中文文档

相关文章:

  • DSP芯片C6678的SRIO及其中断跳转的配置
  • 【Java】I/O 流篇 —— 字节 I/O 流
  • Starlink卫星动力学系统仿真建模第九讲-滑模(SMC)控制算法原理简介及卫星控制应用
  • 深入理解Self-Attention - 原理与等价表示
  • 15.1 智能销售顾问系统架构与业务价值解析:AI 如何重塑销售流程
  • RTOS系统ulTaskNotifyTake怎么知道哪个发送任务通知函数的pxcurrentTCB
  • 4.WebSocket 配置与Nginx 的完美结合
  • react路由总结
  • IDEA搭建SpringBoot,MyBatis,Mysql工程项目
  • 学习threejs,使用createMultiMaterialObject创建多材质对象
  • 小视频压缩实用方法大汇总
  • 6.2 - UART串口数据发送之轮询
  • python-leetcode 42.验证二叉搜索树
  • 嵌入式学习|C语言篇进程间通信(IPC)全面解析与示例
  • 地铁站内导航系统:基于蓝牙Beacon与AR技术的动态路径规划技术深度剖析
  • 【OMCI实践】ONT上线过程的omci消息(五)
  • 23种设计模式的cpp举例
  • 蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
  • 纯电动轻型载货车能量流测试优化研究
  • 系统架构设计:软件工程部分知识概述
  • 营销型网站设计文章/seo课程培训机构
  • html5 css3单页手机网站模板/完整html网页代码案例
  • 中国太平保险集团官方网站/口碑营销的案例
  • design设计网站/新手如何涨1000粉