Go语言搬砖 操作minio

·  阅读 778

这是我参与8月更文挑战的第30天,活动详情查看:8月更文挑战

简介

通过minio快速入门基本了解了minio,接下来使用代码实操一下

快速入门传送门:juejin.cn/post/700167…

客户端

minio官方提供了简单的Go Client SDK客户端,目前最新版本是v7

地址: github.com/minio/minio…

初始化

MinIO client需要以下4个参数来连接与S3兼容的对象存储。

image.png

将4个配置项声明为常量,不允许更改,将client设置全局变量,方便多个函数使用,然后使用init函数在启动项目执行

这里我们不使用https,将userSSl设置为false

const (
   endpoint string = "ip:9000"
   accessKeyID string = "minioadmin"
   secretAccessKey string= "minioadmin"
   useSSL bool = false
)

var (
   client *minio.Client
   err error
)

func init() {
   client, err := minio.New(endpoint, &minio.Options{
      Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
      Secure: useSSL})
   if err != nil {
      log.Fatalln("minio连接错误: ",err)
   }
   log.Printf("%#v\n", client)
}
复制代码

创建bucket

对于bucket相关的api有如下几个

image.png

调用了MakeBucket创建桶,调用BucketExists判断桶是否已存在,,其它还有查看桶列表,删除桶等api

func createBucket()  {
   bucketName := "mymusic"
   err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: "cn-south-1",ObjectLocking: false})
   if err != nil {
      log.Println("创建bucket错误: ",err)
      exists, _ := client.BucketExists(ctx, bucketName)
      if exists {
         log.Printf("bucket: %s已经存在",bucketName)
      }
   } else {
      log.Printf("Successfully created %s\n", bucketName)
   }
}
复制代码

查看bucket列表

调用ListBuckets方法获取一个结果,循环遍历出来

func listBucket() {
   buckets, _ := client.ListBuckets(ctx)
   for _,bucket := range buckets {
      fmt.Println(bucket)
   }
}
复制代码

上传文件

调用FPutObject方法,上传一个文件,其中ContentType可以设置为application/octet-stream,也可以设置为binary/octet-stream,因为是个文本文件,我们这里设置的text,如果是压缩文件设置为zip等

func FileUploader() {
   bucketName := "mymusic"
   objectName := "audit.log"
   filePath := "./audit.log"
   contextType := "application/text"

   object, err := client.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contextType})
   if err != nil {
      log.Println("上传失败:",err)
   }
   log.Printf("Successfully uploaded %s of size %d\n", objectName, object.Size)
}
复制代码

下载文件

调用FGetObject方法,下载文件到本地,并将文件和路径 设定为./audit2.log

func FileGet() {
   bucketName := "mymusic"
   objectName := "audit.log"
   filePath := "./audit2.log"

   err = client.FGetObject(ctx, bucketName, objectName, filePath, minio.GetObjectOptions{})
   if err != nil {
      log.Println("下载错误: ",err)
   }
}
复制代码

生命周期

lifecycleSet函数为设置mymusic这个桶的生命周期为一年,到期自动删除

lifecycleGet函数为获取mymusic这个桶的生命周期信息,并另外为json文件到本地

func lifecycleSet() {
   config := lifecycle.NewConfiguration()
   config.Rules = []lifecycle.Rule{
      {
         ID:     "expire-bucket",
         Status: "Enabled",
         Expiration: lifecycle.Expiration{
            Days: 365,
         },
      },
   }
   _ = client.SetBucketLifecycle(ctx, "mymusic", config)

}

func lifecycleGet() {
   lifecycle, _ := client.GetBucketLifecycle(ctx, "mymusic")
   localLifecycleFile, _ := os.Create("lifecycle.json")
   defer localLifecycleFile.Close()

   encoder := xml.NewEncoder(localLifecycleFile)
   encoder.Indent("  ", "    ")
   encoder.Encode(lifecycle)

}
复制代码

复制文件

文件在bucket之间来回复制,调用CopyObject实现

func FileCopy() {
   src := minio.CopySrcOptions{
      Bucket:"test2",
      Object: "messages",
      MatchModifiedSince: time.Date(2014,time.April, 0, 0, 0, 0, 0, time.UTC),
   }
   dst := minio.CopyDestOptions{
      Bucket:"mymusic",
      Object: "messages",
   }
   object, _ := client.CopyObject(ctx, dst, src)
   log.Printf("Copied %s, successfully to %s - UploadInfo %v\n", dst, src, object)
}
复制代码

删除文件

删除单个文件比较简单,调用RemoveObject方法,传入桶名和文件名就可以了

批量删除的话需要将前缀为test的全部查出来,然后通过 通道的方式传递给RemoveObjects方法

func FilesDelete() {
   bucketName := "mymusic"
   objectName := "audit.log"
   //删除一个文件
   _ = client.RemoveObject(ctx, bucketName, objectName, minio.RemoveObjectOptions{GovernanceBypass: true})

   //批量删除文件
   objectsCh := make(chan minio.ObjectInfo)
   go func() {
      defer close(objectsCh)
      options := minio.ListObjectsOptions{Prefix: "test", Recursive: true}
      for object := range client.ListObjects(ctx,bucketName,options) {
         if object.Err != nil {
            log.Println(object.Err)
         }
         objectsCh <- object
      }
   }()
   client.RemoveObjects(ctx,objectName,objectsCh,minio.RemoveObjectsOptions{})
}
复制代码

API参考

官网给出了大部分api的操作demo

传送门: github.com/minio/minio…

分类:
后端