文件

MinIO Go 客戶端 API 參考 Slack

初始化 MinIO 客戶端物件。

MinIO

package main

import (
	"log"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

func main() {
	endpoint := "play.min.io"
	accessKeyID := "Q3AM3UQ867SPQQA43P2F"
	secretAccessKey := "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"
	useSSL := true

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("%#v\n", minioClient) // minioClient is now setup
}

AWS S3

package main

import (
    "fmt"

    "github.com/minio/minio-go/v7"
    "github.com/minio/minio-go/v7/pkg/credentials"
)

func main() {
        // Initialize minio client object.
        s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{
   	        Creds:  credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""),
	        Secure: true,
        })
        if err != nil {
                fmt.Println(err)
                return
        }
}

儲存桶操作

物件操作

預先簽署的操作

儲存桶策略/通知操作

客戶端自訂設定

MakeBucket

GetObject

PresignedGetObject

SetBucketPolicy

SetAppInfo

PutObject

PresignedPutObject

GetBucketPolicy

ListBuckets

CopyObject

PresignedHeadObject

SetBucketNotification

TraceOn

BucketExists

StatObject

PresignedPostPolicy

GetBucketNotification

TraceOff

RemoveBucket

RemoveObject

RemoveAllBucketNotification

SetS3TransferAccelerate

ListObjects

RemoveObjects

ListenBucketNotification

RemoveIncompleteUpload

SetBucketLifecycle

ListIncompleteUploads

FPutObject

GetBucketLifecycle

SetBucketTagging

FGetObject

SetObjectLockConfig

GetBucketTagging

ComposeObject

GetObjectLockConfig

RemoveBucketTagging

EnableVersioning

SetBucketReplication

DisableVersioning

GetBucketReplication

PutObjectRetention

GetBucketEncryption

RemoveBucketReplication

GetObjectRetention

RemoveBucketEncryption

PutObjectLegalHold

GetObjectLegalHold

SelectObjectContent

PutObjectTagging

GetObjectTagging

RemoveObjectTagging

RestoreObject

GetObjectAttributes

1. 建構函式

New(endpoint string, opts *Options) (*Client, error)

初始化新的客戶端物件。

參數

參數

類型

說明

endpoint

string

與 S3 相容的物件儲存端點

opts

minio.Options

用於建構新客戶端的選項

minio.Options

欄位

類型

說明

opts.Creds

*credentials.Credentials

與 S3 相容的物件儲存存取憑證

opts.Secure

bool

如果為「true」,則 API 請求將是安全的 (HTTPS),否則將是不安全的 (HTTP)

opts.Transport

http.RoundTripper

用於執行 HTTP 交易的自訂傳輸

opts.Region

string

與 S3 相容的物件儲存區域

opts.BucketLookup

BucketLookupType

儲存桶查找類型可以是下列值之一

minio.BucketLookupDNS

minio.BucketLookupPath

minio.BucketLookupAuto

2. 儲存桶操作

MakeBucket(ctx context.Context, bucketName string, opts MakeBucketOptions)

建立新的儲存桶。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

opts

minio.MakeBucketOptions

儲存桶選項,例如要在其中建立儲存桶的 區域。預設值為 us-east-1。下面列出了其他有效值。注意:與 minio 伺服器一起使用時,請使用其設定檔中指定的區域 (預設為 us-east-1)。

us-east-1

us-east-2

us-west-1

us-west-2

ca-central-1

eu-west-1

eu-west-2

eu-west-3

eu-central-1

eu-north-1

ap-east-1

ap-south-1

ap-southeast-1

ap-southeast-2

ap-northeast-1

ap-northeast-2

ap-northeast-3

me-south-1

sa-east-1

us-gov-west-1

us-gov-east-1

cn-north-1

cn-northwest-1

範例

// Create a bucket at region 'us-east-1' with object locking enabled.
err = minioClient.MakeBucket(context.Background(), "mybucket", minio.MakeBucketOptions{Region: "us-east-1", ObjectLocking: true})
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully created mybucket.")

ListBuckets(ctx context.Context) ([]BucketInfo, error)

列出所有儲存桶。

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketList

[]minio.BucketInfo

所有儲存桶的列表

minio.BucketInfo

欄位

類型

說明

bucket.Name

string

儲存桶的名稱

bucket.CreationDate

time.Time

儲存桶建立日期

範例

buckets, err := minioClient.ListBuckets(context.Background())
if err != nil {
    fmt.Println(err)
    return
}
for _, bucket := range buckets {
    fmt.Println(bucket)
}

BucketExists(ctx context.Context, bucketName string) (found bool, err error)

檢查儲存桶是否存在。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

found

bool

表示儲存桶是否存在

err

error

標準錯誤

範例

found, err := minioClient.BucketExists(context.Background(), "mybucket")
if err != nil {
    fmt.Println(err)
    return
}
if found {
    fmt.Println("Bucket found")
}

RemoveBucket(ctx context.Context, bucketName string) error

移除儲存桶,儲存桶必須為空才能成功移除。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

範例

err = minioClient.RemoveBucket(context.Background(), "mybucket")
if err != nil {
    fmt.Println(err)
    return
}

ListObjects(ctx context.Context, bucketName string, opts ListObjectsOptions) <-chan ObjectInfo

列出儲存桶中的物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

opts

minio.ListObjectsOptions

列出物件的選項

回傳值

參數

類型

說明

objectInfo

chan minio.ObjectInfo

讀取 bucket 中所有物件的 channel,物件格式如下所示

minio.ObjectInfo

欄位

類型

說明

objectInfo.Key

string

物件名稱

objectInfo.Size

int64

物件大小

objectInfo.ETag

string

物件的 MD5 檢查碼

objectInfo.LastModified

time.Time

物件最後修改時間

ctx, cancel := context.WithCancel(context.Background())

defer cancel()

objectCh := minioClient.ListObjects(ctx, "mybucket", minio.ListObjectsOptions{
       Prefix: "myprefix",
       Recursive: true,
})
for object := range objectCh {
    if object.Err != nil {
        fmt.Println(object.Err)
        return
    }
    fmt.Println(object)
}

ListIncompleteUploads(ctx context.Context, bucketName, prefix string, recursive bool) <- chan ObjectMultipartInfo

列出 bucket 中部分上傳的物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

prefix

string

部分上傳的物件的前綴

recursive

bool

true 表示遞迴式列出,false 表示以 ‘/’ 分隔的目錄式列出。

回傳值

參數

類型

說明

multiPartInfo

chan minio.ObjectMultipartInfo

發出 multipart 物件,格式如下所示

minio.ObjectMultipartInfo

欄位

類型

說明

multiPartObjInfo.Key

string

未完全上傳的物件名稱

multiPartObjInfo.UploadID

string

未完全上傳的物件的 Upload ID

multiPartObjInfo.Size

int64

未完全上傳的物件大小

範例

isRecursive := true // Recursively list everything at 'myprefix'
multiPartObjectCh := minioClient.ListIncompleteUploads(context.Background(), "mybucket", "myprefix", isRecursive)
for multiPartObject := range multiPartObjectCh {
    if multiPartObject.Err != nil {
        fmt.Println(multiPartObject.Err)
        return
    }
    fmt.Println(multiPartObject)
}

SetBucketTagging(ctx context.Context, bucketName string, tags *tags.Tags) error

設定 bucket 的標籤。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

tags

*tags.Tags

Bucket 標籤

範例

// Create tags from a map.
tags, err := tags.NewTags(map[string]string{
	"Tag1": "Value1",
	"Tag2": "Value2",
}, false)
if err != nil {
	log.Fatalln(err)
}

err = minioClient.SetBucketTagging(context.Background(), "my-bucketname", tags)
if err != nil {
	log.Fatalln(err)
}

GetBucketTagging(ctx context.Context, bucketName string) (*tags.Tags, error)

取得 bucket 的標籤。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

回傳值

參數

類型

說明

tags

*tags.Tags

Bucket 標籤

範例

tags, err := minioClient.GetBucketTagging(context.Background(), "my-bucketname")
if err != nil {
	log.Fatalln(err)
}

fmt.Printf("Fetched Object Tags: %v\n", tags)

RemoveBucketTagging(ctx context.Context, bucketName string) error

移除 bucket 上的所有標籤。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

範例

err := minioClient.RemoveBucketTagging(context.Background(), "my-bucketname")
if err != nil {
	log.Fatalln(err)
}

3. 物件操作

GetObject(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (*Object, error)

回傳物件資料的 stream。 大多數常見的錯誤發生在讀取 stream 時。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.GetObjectOptions

GET 請求的選項,指定其他選項,例如加密、If-Match

minio.GetObjectOptions

欄位

類型

說明

opts.ServerSideEncryption

encrypt.ServerSide

encrypt 套件提供的介面,用於指定伺服器端加密。(更多資訊請參閱 https://godoc.org/github.com/minio/minio-go/v7)

opts.Internal

minio.AdvancedGetOptions

此選項供 MinIO 伺服器內部使用。除非應用程式知道預期的用途,否則不應設定此選項。

回傳值

參數

類型

說明

object

*minio.Object

minio.Object 代表物件讀取器。它實作 io.Reader、io.Seeker、io.ReaderAt 和 io.Closer 介面。

範例

object, err := minioClient.GetObject(context.Background(), "mybucket", "myobject", minio.GetObjectOptions{})
if err != nil {
    fmt.Println(err)
    return
}
defer object.Close()

localFile, err := os.Create("/tmp/local-file.jpg")
if err != nil {
    fmt.Println(err)
    return
}
defer localFile.Close()

if _, err = io.Copy(localFile, object); err != nil {
    fmt.Println(err)
    return
}

FGetObject(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error

下載物件並將其儲存為本地檔案系統中的檔案。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

filePath

string

下載物件的路徑

opts

minio.GetObjectOptions

GET 請求的選項,指定其他選項,例如加密、If-Match

範例

err = minioClient.FGetObject(context.Background(), "mybucket", "myobject", "/tmp/myobject", minio.GetObjectOptions{})
if err != nil {
    fmt.Println(err)
    return
}

PutObjectFanOut(ctx context.Context, bucket string, body io.Reader, fanOutReq …PutObjectFanOutRequest) ([]PutObjectFanOutResponse, error)

PutObject 的變體,不是從單個 stream 寫入單個物件,而是寫入多個物件,透過 PutObjectFanOutRequest 清單定義。 PutObjectFanOutRequest 中的每個項目都帶有物件 keyname 和任何相關的 metadata。 Key 為必填,*PutObjectFanOutRequest 中的其他選項為選填。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

fanOutData

io.Reader

任何實作 io.Reader 的 Go 型別

fanOutReq

minio.PutObjectFanOutRequest

使用者輸入清單,其中包含將在伺服器上建立的所有物件

minio.PutObjectFanOutRequest

欄位

類型

說明

Entries

[]minio.PutObjectFanOutEntyry

物件扇出項目的清單

Checksums

map[string]string

輸入資料的檢查碼

SSE

_encrypt.ServerSide

整個扇出的加密設定

minio.PutObjectFanOutEntry

欄位

類型

說明

Key

string

物件名稱

UserMetadata

map[string]string

使用者 metadata 的 Map

UserTags

map[string]string

使用者物件標籤的 Map

ContentType

string

物件的內容類型,例如 “application/text”

ContentEncoding

string

物件的內容編碼,例如 “gzip”

ContentDisposition

string

物件的內容處置,“inline”

ContentLanguage

string

物件的內容語言,例如 “French”

CacheControl

string

用於指定請求和回應中快取機制的指示詞,例如 “max-age=600”

Retention

minio.RetentionMode

要設定的保留模式,例如 “COMPLIANCE”

RetainUntilDate

time.Time

保留有效期限

minio.PutObjectFanOutResponse

欄位

類型

說明

Key

string

物件名稱

ETag

string

物件的 ETag 不透明唯一值

VersionID

string

上傳物件的 VersionID

LastModified

_time.Time

最新物件的最後修改時間

Error

error

僅當特定物件的扇出失敗時,才為非 nil

PutObject(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,opts PutObjectOptions) (info UploadInfo, err error)

在單個 PUT 操作中上傳小於 128MiB 的物件。 對於大小超過 128MiB 的物件,PutObject 會根據實際檔案大小,以 128MiB 或更大的部分無縫上傳物件。 物件的最大上傳大小為 5TB。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

reader

io.Reader

任何實作 io.Reader 的 Go 型別

objectSize

int64

要上傳的物件大小。 如果 stream 大小未知,請傳遞 -1(警告:傳遞 -1 將分配大量記憶體)

opts

minio.PutObjectOptions

允許使用者設定選填的自訂 metadata、內容標頭、加密金鑰和 multipart 上傳操作的執行緒數。

minio.PutObjectOptions

欄位

類型

說明

opts.UserMetadata

map[string]string

使用者 metadata 的 Map

opts.UserTags

map[string]string

使用者物件標籤的 Map

opts.Progress

io.Reader

用於取得上傳進度的讀取器

opts.ContentType

string

物件的內容類型,例如 “application/text”

opts.ContentEncoding

string

物件的內容編碼,例如 “gzip”

opts.ContentDisposition

string

物件的內容處置,“inline”

opts.ContentLanguage

string

物件的內容語言,例如 “French”

opts.CacheControl

string

用於指定請求和回應中快取機制的指示詞,例如 “max-age=600”

opts.Mode

*minio.RetentionMode

要設定的保留模式,例如 “COMPLIANCE”

opts.RetainUntilDate

*time.Time

保留有效期限

opts.ServerSideEncryption

encrypt.ServerSide

encrypt 套件提供的介面,用於指定伺服器端加密。(更多資訊請參閱 https://godoc.org/github.com/minio/minio-go/v7)

opts.StorageClass

string

指定物件的儲存類別。 MinIO 伺服器支援的值為 REDUCED_REDUNDANCYSTANDARD

opts.WebsiteRedirectLocation

string

為物件指定重新導向,到同一個 bucket 中的另一個物件或外部 URL。

opts.SendContentMd5

bool

指定是否要使用 PutObject 操作傳送 content-md5 標頭。 請注意,設定此旗標將會因為記憶體中的 md5sum 計算而導致更高的記憶體使用率。

opts.PartSize

uint64

指定用於上傳物件的自訂部分大小

opts.Internal

minio.AdvancedPutOptions

此選項供 MinIO 伺服器內部使用,除非應用程式知道預期的用途,否則不應設定此選項。

minio.UploadInfo

欄位

類型

說明

info.ETag

string

新物件的 ETag

info.VersionID

string

新物件的版本識別碼

範例

file, err := os.Open("my-testfile")
if err != nil {
    fmt.Println(err)
    return
}
defer file.Close()

fileStat, err := file.Stat()
if err != nil {
    fmt.Println(err)
    return
}

uploadInfo, err := minioClient.PutObject(context.Background(), "mybucket", "myobject", file, fileStat.Size(), minio.PutObjectOptions{ContentType:"application/octet-stream"})
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully uploaded bytes: ", uploadInfo)

minio-go SDK 版本 v3.0.3 中提供的 API 方法 PutObjectWithSize、PutObjectWithMetadata、PutObjectStreaming 和 PutObjectWithProgress 已由接受 PutObjectOptions struct 指標的新 PutObject 呼叫變體取代。

CopyObject(ctx context.Context, dst CopyDestOptions, src CopySrcOptions) (UploadInfo, error)

透過伺服器端複製現有物件來建立或取代物件。 它支援條件式複製、複製物件的一部分以及目標的伺服器端加密和來源的解密。 有關更多詳細資訊,請參閱 CopySrcOptionsDestinationInfo 型別。

若要將多個來源物件複製到單個目標物件,請參閱 ComposeObject API。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

dst

minio.CopyDestOptions

描述目標物件的引數

src

minio.CopySrcOptions

描述來源物件的引數

minio.UploadInfo

欄位

類型

說明

info.ETag

string

新物件的 ETag

info.VersionID

string

新物件的版本識別碼

範例

// Use-case 1: Simple copy object with no conditions.
// Source object
srcOpts := minio.CopySrcOptions{
    Bucket: "my-sourcebucketname",
    Object: "my-sourceobjectname",
}

// Destination object
dstOpts := minio.CopyDestOptions{
    Bucket: "my-bucketname",
    Object: "my-objectname",
}

// Copy object call
uploadInfo, err := minioClient.CopyObject(context.Background(), dst, src)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println("Successfully copied object:", uploadInfo)
// Use-case 2:
// Copy object with copy-conditions, and copying only part of the source object.
// 1. that matches a given ETag
// 2. and modified after 1st April 2014
// 3. but unmodified since 23rd April 2014
// 4. copy only first 1MiB of object.

// Source object
srcOpts := minio.CopySrcOptions{
    Bucket: "my-sourcebucketname",
    Object: "my-sourceobjectname",
    MatchETag: "31624deb84149d2f8ef9c385918b653a",
    MatchModifiedSince: time.Date(2014, time.April, 1, 0, 0, 0, 0, time.UTC),
    MatchUnmodifiedSince: time.Date(2014, time.April, 23, 0, 0, 0, 0, time.UTC),
    Start: 0,
    End: 1024*1024-1,
}


// Destination object
dstOpts := minio.CopyDestOptions{
    Bucket: "my-bucketname",
    Object: "my-objectname",
}

// Copy object call
_, err = minioClient.CopyObject(context.Background(), dst, src)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println("Successfully copied object:", uploadInfo)

ComposeObject(ctx context.Context, dst minio.CopyDestOptions, srcs …minio.CopySrcOptions) (UploadInfo, error)

透過使用伺服器端複製串連來源物件清單來建立物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

dst

minio.CopyDestOptions

包含要建立的物件資訊的 Struct。

srcs

…minio.CopySrcOptions

包含要按順序串連的來源物件資訊的 struct Slice。

minio.UploadInfo

欄位

類型

說明

info.ETag

string

新物件的 ETag

info.VersionID

string

新物件的版本識別碼

範例

// Prepare source decryption key (here we assume same key to
// decrypt all source objects.)
sseSrc := encrypt.DefaultPBKDF([]byte("password"), []byte("salt"))

// Source objects to concatenate. We also specify decryption
// key for each
src1Opts := minio.CopySrcOptions{
    Bucket: "bucket1",
    Object: "object1",
    Encryption: sseSrc,
    MatchETag: "31624deb84149d2f8ef9c385918b653a",
}

src2Opts := minio.CopySrcOptions{
    Bucket: "bucket2",
    Object: "object2",
    Encryption: sseSrc,
    MatchETag: "f8ef9c385918b653a31624deb84149d2",
}

src3Opts := minio.CopySrcOptions{
    Bucket: "bucket3",
    Object: "object3",
    Encryption: sseSrc,
    MatchETag: "5918b653a31624deb84149d2f8ef9c38",
}

// Prepare destination encryption key
sseDst := encrypt.DefaultPBKDF([]byte("new-password"), []byte("new-salt"))

// Create destination info
dstOpts := CopyDestOptions{
    Bucket: "bucket",
    Object: "object",
    Encryption: sseDst,
}

// Compose object call by concatenating multiple source files.
uploadInfo, err := minioClient.ComposeObject(context.Background(), dst, srcs...)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println("Composed object successfully:", uploadInfo)

FPutObject(ctx context.Context, bucketName, objectName, filePath, opts PutObjectOptions) (info UploadInfo, err error)

將檔案內容從檔案上傳到 objectName。

FPutObject 在單個 PUT 操作中上傳小於 128MiB 的物件。 對於大小超過 128MiB 的物件,FPutObject 會根據實際檔案大小,以 128MiB 或更大的區塊無縫上傳物件。 物件的最大上傳大小為 5TB。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

filePath

string

要上傳的檔案路徑

opts

minio.PutObjectOptions

Struct 的指標,允許使用者設定選填的自訂 metadata、content-type、content-encoding、content-disposition、content-language 和 cache-control 標頭,傳遞加密模組以加密物件,並可選擇設定 multipart put 操作的執行緒數。

minio.UploadInfo

欄位

類型

說明

info.ETag

string

新物件的 ETag

info.VersionID

string

新物件的版本識別碼

範例

uploadInfo, err := minioClient.FPutObject(context.Background(), "my-bucketname", "my-objectname", "my-filename.csv", minio.PutObjectOptions{
	ContentType: "application/csv",
});
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully uploaded object: ", uploadInfo)

StatObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error)

取得物件的 metadata。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.StatObjectOptions

用於取得資訊/stat 請求的選項,指定其他選項,例如加密、If-Match

回傳值

參數

類型

說明

objInfo

minio.ObjectInfo

物件 stat 資訊

minio.ObjectInfo

欄位

類型

說明

objInfo.LastModified

time.Time

物件最後修改時間

objInfo.ETag

string

物件的 MD5 檢查碼

objInfo.ContentType

string

物件的內容類型

objInfo.Size

int64

物件大小

範例

objInfo, err := minioClient.StatObject(context.Background(), "mybucket", "myobject", minio.StatObjectOptions{})
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(objInfo)

RemoveObject(ctx context.Context, bucketName, objectName string, opts minio.RemoveObjectOptions) error

使用某些指定選項移除物件

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.RemoveObjectOptions

允許使用者設定選項

minio.RemoveObjectOptions

欄位

類型

說明

opts.GovernanceBypass

bool

設定 bypass governance 標頭以刪除以 GOVERNANCE 模式鎖定的物件

opts.VersionID

string

要刪除的物件的版本 ID

opts.Internal

minio.AdvancedRemoveOptions

此選項供 MinIO 伺服器內部使用,除非應用程式知道預期的用途,否則不應設定此選項。

opts := minio.RemoveObjectOptions {
		GovernanceBypass: true,
		VersionID: "myversionid",
		}
err = minioClient.RemoveObject(context.Background(), "mybucket", "myobject", opts)
if err != nil {
    fmt.Println(err)
    return
}

PutObjectRetention(ctx context.Context, bucketName, objectName string, opts minio.PutObjectRetentionOptions) error

將物件保留鎖套用至物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.PutObjectRetentionOptions

允許使用者設定保留模式、到期日和版本 ID 等選項

RemoveObjects(ctx context.Context, bucketName string, objectsCh <-chan ObjectInfo, opts RemoveObjectsOptions) <-chan RemoveObjectError

移除從輸入通道取得的物件清單。此呼叫會一次向伺服器發送最多 1000 個物件的刪除請求。觀察到的錯誤會透過錯誤通道傳送。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectsCh

chan minio.ObjectInfo

要移除的物件通道

opts

minio.RemoveObjectsOptions

允許使用者設定選項

minio.RemoveObjectsOptions

欄位

類型

說明

opts.GovernanceBypass

bool

設定 bypass governance 標頭以刪除以 GOVERNANCE 模式鎖定的物件

傳回值

參數

類型

說明

errorCh

<-chan minio.RemoveObjectError

接收刪除期間觀察到的錯誤的唯讀通道。

objectsCh := make(chan minio.ObjectInfo)

// Send object names that are needed to be removed to objectsCh
go func() {
	defer close(objectsCh)
	// List all objects from a bucket-name with a matching prefix.
	for object := range minioClient.ListObjects(context.Background(), "my-bucketname", "my-prefixname", true, nil) {
		if object.Err != nil {
			log.Fatalln(object.Err)
		}
		objectsCh <- object
	}
}()

opts := minio.RemoveObjectsOptions{
	GovernanceBypass: true,
}

for rErr := range minioClient.RemoveObjects(context.Background(), "my-bucketname", objectsCh, opts) {
    fmt.Println("Error detected during deletion: ", rErr)
}

GetObjectRetention(ctx context.Context, bucketName, objectName, versionID string) (mode *RetentionMode, retainUntilDate *time.Time, err error)

傳回在指定物件上設定的保留。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

versionID

string

物件的版本 ID

err = minioClient.PutObjectRetention(context.Background(), "mybucket", "myobject", "")
if err != nil {
    fmt.Println(err)
    return
}

PutObjectLegalHold(ctx context.Context, bucketName, objectName string, opts minio.PutObjectLegalHoldOptions) error

將法律保留套用至物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.PutObjectLegalHoldOptions

允許使用者設定狀態和版本 ID 等選項

minio.PutObjectLegalHoldOptions

欄位

類型

說明

opts.Status

*minio.LegalHoldStatus

要設定的法律保留狀態

opts.VersionID

string

要套用保留的物件版本 ID

s := minio.LegalHoldEnabled
opts := minio.PutObjectLegalHoldOptions {
    Status: &s,
}
err = minioClient.PutObjectLegalHold(context.Background(), "mybucket", "myobject", opts)
if err != nil {
    fmt.Println(err)
    return
}

GetObjectLegalHold(ctx context.Context, bucketName, objectName, versionID string) (status *LegalHoldStatus, err error)

傳回指定物件的法律保留狀態。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.GetObjectLegalHoldOptions

允許使用者設定版本 ID 等選項

opts := minio.GetObjectLegalHoldOptions{}
err = minioClient.GetObjectLegalHold(context.Background(), "mybucket", "myobject", opts)
if err != nil {
    fmt.Println(err)
    return
}

SelectObjectContent(ctx context.Context, bucketName string, objectsName string, expression string, options SelectObjectOptions) *SelectResults

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

ctx

context.Context

請求上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

options

SelectObjectOptions

查詢選項

傳回值

參數

類型

說明

SelectResults

SelectResults

是一個 io.ReadCloser 物件,可以直接傳遞給 csv.NewReader 以進行輸出處理。

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})

	opts := minio.SelectObjectOptions{
		Expression:     "select count(*) from s3object",
		ExpressionType: minio.QueryExpressionTypeSQL,
		InputSerialization: minio.SelectObjectInputSerialization{
			CompressionType: minio.SelectCompressionNONE,
			CSV: &minio.CSVInputOptions{
				FileHeaderInfo:  minio.CSVFileHeaderInfoNone,
				RecordDelimiter: "\n",
				FieldDelimiter:  ",",
			},
		},
		OutputSerialization: minio.SelectObjectOutputSerialization{
			CSV: &minio.CSVOutputOptions{
				RecordDelimiter: "\n",
				FieldDelimiter:  ",",
			},
		},
	}

	reader, err := s3Client.SelectObjectContent(context.Background(), "mycsvbucket", "mycsv.csv", opts)
	if err != nil {
		log.Fatalln(err)
	}
	defer reader.Close()

	if _, err := io.Copy(os.Stdout, reader); err != nil {
		log.Fatalln(err)
	}

PutObjectTagging(ctx context.Context, bucketName, objectName string, otags *tags.Tags) error

將新的物件標籤設定到給定的物件,取代/覆寫任何現有的標籤。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

objectTags

*tags.Tags

具有物件標籤的鍵和值的對應

範例

err = minioClient.PutObjectTagging(context.Background(), bucketName, objectName, objectTags)
if err != nil {
    fmt.Println(err)
    return
}

GetObjectTagging(ctx context.Context, bucketName, objectName string) (*tags.Tags, error)

從給定的物件擷取物件標籤

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

範例

tags, err = minioClient.GetObjectTagging(context.Background(), bucketName, objectName)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Printf("Fetched Tags: %s", tags)

RemoveObjectTagging(ctx context.Context, bucketName, objectName string) error

從給定的物件移除物件標籤

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

範例

err = minioClient.RemoveObjectTagging(context.Background(), bucketName, objectName)
if err != nil {
    fmt.Println(err)
    return
}

RestoreObject(ctx context.Context, bucketName, objectName, versionID string, opts minio.RestoreRequest) error

在封存的物件上還原或執行 SQL 操作

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

versionID

string

物件的版本 ID

opts

_minio.RestoreRequest

還原請求選項

範例

opts := minio.RestoreRequest{}
opts.SetDays(1)
opts.SetGlacierJobParameters(minio.GlacierJobParameters{Tier: minio.TierStandard})

err = s3Client.RestoreObject(context.Background(), "your-bucket", "your-object", "", opts)
if err != nil {
    log.Fatalln(err)
}

GetObjectAttributes(ctx context.Context, bucketName, objectName string, opts ObjectAttributesOptions) (*ObjectAttributes, error)

回傳物件資料的 stream。 大多數常見的錯誤發生在讀取 stream 時。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

opts

minio.ObjectAttributesOptions

用於分頁和選擇物件屬性的設定

minio.ObjectAttributesOptions

欄位

類型

說明

opts.ServerSideEncryption

encrypt.ServerSide

encrypt 套件提供的介面,用於指定伺服器端加密。(更多資訊請參閱 https://godoc.org/github.com/minio/minio-go/v7)

opts.MaxParts

_int

此選項定義 API 應傳回多少個部分

opts.VersionID

_string

VersionID 定義將使用哪個版本的物件

opts.PartNumberMarker

_int

此選項定義分頁將從哪個部分編號開始,編號等於 PartNumberMarker 的部分將不會包含在回應中

回傳值

參數

類型

說明

objectAttributes

*minio.ObjectAttributes

minio.ObjectAttributes 包含有關物件及其部分資訊。

範例

objectAttributes, err := c.GetObjectAttributes(
    context.Background(), 
    "your-bucket", 
    "your-object", 
    minio.ObjectAttributesOptions{
        VersionID:"object-version-id",
        NextPartMarker:0,
        MaxParts:100,
    })

if err != nil {
    fmt.Println(err)
	return
}

fmt.Println(objectAttributes)

RemoveIncompleteUpload(ctx context.Context, bucketName, objectName string) error

移除部分上傳的物件。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

範例

err = minioClient.RemoveIncompleteUpload(context.Background(), "mybucket", "myobject")
if err != nil {
    fmt.Println(err)
    return
}

4. 預先簽署的操作

PresignedGetObject(ctx context.Context, bucketName, objectName string, expiry time.Duration, reqParams url.Values) (*url.URL, error)

為 HTTP GET 操作產生預先簽署的 URL。即使儲存桶是私有的,瀏覽器/行動用戶端也可以指向此 URL 以直接下載物件。此預先簽署的 URL 可以有一個相關聯的到期時間(以秒為單位),超過此時間後將不再有效。最大到期時間為 604800 秒(即 7 天),最小為 1 秒。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

expiry

time.Duration

預先簽署 URL 的到期時間(以秒為單位)

reqParams

url.Values

其他回應標頭覆寫支援 response-expiresresponse-content-typeresponse-cache-controlresponse-content-disposition

範例

// Set request parameters for content-disposition.
reqParams := make(url.Values)
reqParams.Set("response-content-disposition", "attachment; filename=\"your-filename.txt\"")

// Generates a presigned url which expires in a day.
presignedURL, err := minioClient.PresignedGetObject(context.Background(), "mybucket", "myobject", time.Second * 24 * 60 * 60, reqParams)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully generated presigned URL", presignedURL)

PresignedPutObject(ctx context.Context, bucketName, objectName string, expiry time.Duration) (*url.URL, error)

為 HTTP PUT 操作產生預先簽署的 URL。即使儲存桶是私有的,瀏覽器/行動用戶端也可以指向此 URL 以將物件直接上傳到儲存桶。此預先簽署的 URL 可以有一個相關聯的到期時間(以秒為單位),超過此時間後將不再有效。預設到期時間設定為 7 天。

注意:您只能使用指定的物件名稱上傳到 S3。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

expiry

time.Duration

預先簽署 URL 的到期時間(以秒為單位)

範例

// Generates a url which expires in a day.
expiry := time.Second * 24 * 60 * 60 // 1 day.
presignedURL, err := minioClient.PresignedPutObject(context.Background(), "mybucket", "myobject", expiry)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully generated presigned URL", presignedURL)

PresignedHeadObject(ctx context.Context, bucketName, objectName string, expiry time.Duration, reqParams url.Values) (*url.URL, error)

為 HTTP HEAD 操作產生預先簽署的 URL。即使儲存桶是私有的,瀏覽器/行動用戶端也可以指向此 URL 以直接從物件取得中繼資料。此預先簽署的 URL 可以有一個相關聯的到期時間(以秒為單位),超過此時間後將不再有效。預設到期時間設定為 7 天。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

objectName

string

物件名稱

expiry

time.Duration

預先簽署 URL 的到期時間(以秒為單位)

reqParams

url.Values

其他回應標頭覆寫支援 response-expiresresponse-content-typeresponse-cache-controlresponse-content-disposition

範例

// Set request parameters for content-disposition.
reqParams := make(url.Values)
reqParams.Set("response-content-disposition", "attachment; filename=\"your-filename.txt\"")

// Generates a presigned url which expires in a day.
presignedURL, err := minioClient.PresignedHeadObject(context.Background(), "mybucket", "myobject", time.Second * 24 * 60 * 60, reqParams)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Successfully generated presigned URL", presignedURL)

PresignedPostPolicy(ctx context.Context, post PostPolicy) (*url.URL, map[string]string, error)

允許為 POST 操作的預先簽署 URL 設定原則條件。可以設定接收物件上傳的儲存桶名稱、金鑰名稱前綴、到期原則等原則。

// Initialize policy condition config.
policy := minio.NewPostPolicy()

// Apply upload policy restrictions:
policy.SetBucket("mybucket")
policy.SetKey("myobject")
policy.SetExpires(time.Now().UTC().AddDate(0, 0, 10)) // expires in 10 days

// Only allow 'png' images.
policy.SetContentType("image/png")

// Only allow content size in range 1KB to 1MB.
policy.SetContentLengthRange(1024, 1024*1024)

// Add a user metadata using the key "custom" and value "user"
policy.SetUserMetadata("custom", "user")

// Get the POST form key/value object:
url, formData, err := minioClient.PresignedPostPolicy(context.Background(), policy)
if err != nil {
    fmt.Println(err)
    return
}

// POST your content from the command line using `curl`
fmt.Printf("curl ")
for k, v := range formData {
    fmt.Printf("-F %s=%s ", k, v)
}
fmt.Printf("-F file=@/etc/bash.bashrc ")
fmt.Printf("%s\n", url)

5. 儲存桶原則/通知操作

SetBucketPolicy(ctx context.Context, bucketname, policy string) error

設定儲存桶或物件前綴的存取權限。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

policy

string

要設定的原則

傳回值

參數

類型

說明

err

error

標準錯誤

範例

policy := `{"Version": "2012-10-17","Statement": [{"Action": ["s3:GetObject"],"Effect": "Allow","Principal": {"AWS": ["*"]},"Resource": ["arn:aws:s3:::my-bucketname/*"],"Sid": ""}]}`

err = minioClient.SetBucketPolicy(context.Background(), "my-bucketname", policy)
if err != nil {
    fmt.Println(err)
    return
}

GetBucketPolicy(ctx context.Context, bucketName string) (policy string, error)

取得儲存桶或前綴的存取權限。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

policy

string

從伺服器傳回的原則

err

error

標準錯誤

範例

policy, err := minioClient.GetBucketPolicy(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

GetBucketNotification(ctx context.Context, bucketName string) (notification.Configuration, error)

取得儲存桶上的通知設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

config

notification.Configuration

包含所有通知設定的結構

err

error

標準錯誤

範例

bucketNotification, err := minioClient.GetBucketNotification(context.Background(), "mybucket")
if err != nil {
    fmt.Println("Failed to get bucket notification configurations for mybucket", err)
    return
}

for _, queueConfig := range bucketNotification.QueueConfigs {
    for _, e := range queueConfig.Events {
        fmt.Println(e + " event is enabled")
    }
}

SetBucketNotification(ctx context.Context, bucketName string, config notification.Configuration) error

在儲存桶上設定新的儲存桶通知。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

config

notification.Configuration

表示要傳送到設定的 Web 服務的 XML

傳回值

參數

類型

說明

err

error

標準錯誤

範例

queueArn := notification.NewArn("aws", "sqs", "us-east-1", "804605494417", "PhotoUpdate")

queueConfig := notification.NewConfig(queueArn)
queueConfig.AddEvents(minio.ObjectCreatedAll, minio.ObjectRemovedAll)
queueConfig.AddFilterPrefix("photos/")
queueConfig.AddFilterSuffix(".jpg")

config := notification.Configuration{}
config.AddQueue(queueConfig)

err = minioClient.SetBucketNotification(context.Background(), "mybucket", config)
if err != nil {
    fmt.Println("Unable to set the bucket notification: ", err)
    return
}

RemoveAllBucketNotification(ctx context.Context, bucketName string) error

移除儲存桶上所有設定的儲存桶通知。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

err

error

標準錯誤

範例

err = minioClient.RemoveAllBucketNotification(context.Background(), "mybucket")
if err != nil {
    fmt.Println("Unable to remove bucket notifications.", err)
    return
}

ListenBucketNotification(context context.Context, bucketName, prefix, suffix string, events []string) <-chan notification.Info

ListenBucketNotification API 透過通知通道接收儲存桶通知事件。傳回的通知通道有兩個欄位「Records」和「Err」。

  • 「Records」保存從伺服器收到的通知。

  • 「Err」表示處理接收到的通知時發生的任何錯誤。

注意:通知通道會在第一次發生錯誤時關閉。

參數

參數

類型

說明

bucketName

string

要監聽通知的儲存桶

prefix

string

要篩選通知的物件金鑰前綴

suffix

string

要篩選通知的物件金鑰後綴

events

[]string

針對特定事件類型啟用通知

傳回值

參數

類型

說明

notificationInfo

chan notification.Info

儲存桶通知的通道

minio.NotificationInfo

|欄位 |類型 |描述 | |notificationInfo.Records | []notification.Event | 通知事件的集合 | |notificationInfo.Err | error | 攜帶操作期間發生的任何錯誤(標準錯誤) |

範例

// Listen for bucket notifications on "mybucket" filtered by prefix, suffix and events.
for notificationInfo := range minioClient.ListenBucketNotification(context.Background(), "mybucket", "myprefix/", ".mysuffix", []string{
    "s3:ObjectCreated:*",
    "s3:ObjectAccessed:*",
    "s3:ObjectRemoved:*",
    }) {
    if notificationInfo.Err != nil {
        fmt.Println(notificationInfo.Err)
    }
    fmt.Println(notificationInfo)
}

ListenNotification(context context.Context, prefix, suffix string, events []string) <-chan notification.Info

ListenNotification API 透過通知通道接收儲存桶和物件通知事件。傳回的通知通道有兩個欄位「Records」和「Err」。

  • 「Records」保存從伺服器收到的通知。

  • 「Err」表示處理接收到的通知時發生的任何錯誤。

注意:通知通道會在第一次發生錯誤時關閉。

參數

參數

類型

說明

bucketName

string

要監聽通知的儲存桶

prefix

string

要篩選通知的物件金鑰前綴

suffix

string

要篩選通知的物件金鑰後綴

events

[]string

針對特定事件類型啟用通知

傳回值

參數

類型

說明

notificationInfo

chan notification.Info

讀取所有通知的通道

minio.NotificationInfo

|欄位 |類型 |描述 | |notificationInfo.Records | []notification.Event | 通知事件的集合 | |notificationInfo.Err | error | 攜帶操作期間發生的任何錯誤(標準錯誤) |

範例

// Listen for bucket notifications on "mybucket" filtered by prefix, suffix and events.
for notificationInfo := range minioClient.ListenNotification(context.Background(), "myprefix/", ".mysuffix", []string{
    "s3:BucketCreated:*",
    "s3:BucketRemoved:*",
    "s3:ObjectCreated:*",
    "s3:ObjectAccessed:*",
    "s3:ObjectRemoved:*",
    }) {
    if notificationInfo.Err != nil {
        fmt.Println(notificationInfo.Err)
    }
    fmt.Println(notificationInfo)
}

SetBucketLifecycle(ctx context.Context, bucketname, config *lifecycle.Configuration) error

設定儲存桶或物件前綴的生命週期。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

config

lifecycle.Configuration

要設定的生命週期

傳回值

參數

類型

說明

err

error

標準錯誤

範例

config := lifecycle.NewConfiguration()
config.Rules = []lifecycle.Rule{
  {
    ID:     "expire-bucket",
    Status: "Enabled",
    Expiration: lifecycle.Expiration{
       Days: 365,
    },
  },
}

err = minioClient.SetBucketLifecycle(context.Background(), "my-bucketname", config)
if err != nil {
    fmt.Println(err)
    return
}

GetBucketLifecycle(ctx context.Context, bucketName string) (*lifecycle.Configuration error)

取得儲存桶或前綴的生命週期。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

config

lifecycle.Configuration

從伺服器返回的生命週期

err

error

標準錯誤

範例

lifecycle, err := minioClient.GetBucketLifecycle(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

SetBucketEncryption(ctx context.Context, bucketname string, config sse.Configuration) error

設定儲存桶上的預設加密設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

config

sse.Configuration

用於存放要設定的預設加密設定的結構

傳回值

參數

類型

說明

err

error

標準錯誤

範例

s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{
	Creds:  credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""),
	Secure: true,
})
if err != nil {
    log.Fatalln(err)
}

// Set default encryption configuration on an S3 bucket
err = s3Client.SetBucketEncryption(context.Background(), "my-bucketname", sse.NewConfigurationSSES3())
if err != nil {
    log.Fatalln(err)
}

GetBucketEncryption(ctx context.Context, bucketName string) (*sse.Configuration, error)

取得儲存桶上設定的預設加密設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

config

sse.Configuration

用於存放預設加密設定的結構

err

error

標準錯誤

範例

s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{
	Creds:  credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""),
	Secure: true,
})
if err != nil {
    log.Fatalln(err)
}

// Get default encryption configuration set on an S3 bucket and print it out
encryptionConfig, err := s3Client.GetBucketEncryption(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}
fmt.Printf("%+v\n", encryptionConfig)

RemoveBucketEncryption(ctx context.Context, bucketName string) (error)

移除儲存桶上設定的預設加密設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

err

error

標準錯誤

範例

err := s3Client.RemoveBucketEncryption(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}
// "my-bucket" is successfully deleted/removed.

SetObjectLockConfig(ctx context.Context, bucketname, mode *RetentionMode, validity *uint, unit *ValidityUnit) error

在給定的儲存桶中設定物件鎖定設定。mode、validity 和 unit 要嘛都設定,要嘛都設定為 nil。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

mode

RetentionMode

要設定的保留模式

validity

uint

要設定的有效期限

unit

ValidityUnit

有效期限的單位

傳回值

參數

類型

說明

err

error

標準錯誤

範例

mode := Governance
validity := uint(30)
unit := Days

err = minioClient.SetObjectLockConfig(context.Background(), "my-bucketname", &mode, &validity, &unit)
if err != nil {
    fmt.Println(err)
    return
}

GetObjectLockConfig(ctx context.Context, bucketName string) (objectLock,*RetentionMode, *uint, *ValidityUnit, error)

取得給定儲存桶的物件鎖定設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

objectLock

objectLock

鎖定啟用狀態

mode

RetentionMode

目前的保留模式

validity

uint

目前的有效期限

unit

ValidityUnit

有效期限的單位

err

error

標準錯誤

範例

enabled, mode, validity, unit, err := minioClient.GetObjectLockConfig(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}
fmt.Println("object lock is %s for this bucket",enabled)
if mode != nil {
	fmt.Printf("%v mode is enabled for %v %v for bucket 'my-bucketname'\n", *mode, *validity, *unit)
} else {
	fmt.Println("No mode is enabled for bucket 'my-bucketname'")
}

EnableVersioning(ctx context.Context, bucketName string) error

啟用儲存桶版本控制支援。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

err

error

標準錯誤

範例

err := minioClient.EnableVersioning(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

fmt.Println("versioning enabled for bucket 'my-bucketname'")

DisableVersioning(ctx context.Context, bucketName) error

停用儲存桶版本控制支援。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

err

error

標準錯誤

範例

err := minioClient.DisableVersioning(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

fmt.Println("versioning disabled for bucket 'my-bucketname'")

GetBucketVersioning(ctx context.Context, bucketName string) (BucketVersioningConfiguration, error)

取得儲存桶上設定的版本控制設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

configuration

minio.BucketVersioningConfiguration

用於存放版本控制設定的結構

err

error

標準錯誤

範例

s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{
	Creds:  credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""),
	Secure: true,
})
if err != nil {
    log.Fatalln(err)
}

// Get versioning configuration set on an S3 bucket and print it out
versioningConfig, err := s3Client.GetBucketVersioning(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}
fmt.Printf("%+v\n", versioningConfig)

SetBucketReplication(ctx context.Context, bucketname, cfg replication.Config) error

在儲存桶上設定複寫設定。角色可以透過先在 MinIO 上使用 mc admin bucket remote set 定義複寫目標,將來源和目的儲存桶與複寫端點相關聯來取得。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

cfg

replication.Config

要設定的複寫設定

傳回值

參數

類型

說明

err

error

標準錯誤

範例

replicationStr := `<ReplicationConfiguration>
   <Role></Role>
   <Rule>
      <DeleteMarkerReplication>
         <Status>Disabled</Status>
      </DeleteMarkerReplication>
      <Destination>
         <Bucket>string</Bucket>
         <StorageClass>string</StorageClass>
      </Destination>
      <Filter>
         <And>
            <Prefix>string</Prefix>
            <Tag>
               <Key>string</Key>
               <Value>string</Value>
            </Tag>
            ...
         </And>
         <Prefix>string</Prefix>
         <Tag>
            <Key>string</Key>
            <Value>string</Value>
         </Tag>
      </Filter>
      <ID>string</ID>
      <Prefix>string</Prefix>
      <Priority>integer</Priority>
      <Status>string</Status>
   </Rule>
</ReplicationConfiguration>`
replicationConfig := replication.Config{}
if err := xml.Unmarshal([]byte(replicationStr), &replicationConfig); err != nil {
    log.Fatalln(err)
}
cfg.Role := "arn:minio:s3::598361bf-3cec-49a7-b529-ce870a34d759:*"
err = minioClient.SetBucketReplication(context.Background(), "my-bucketname", replicationConfig)
if err != nil {
    fmt.Println(err)
    return
}

GetBucketReplication(ctx context.Context, bucketName string) (replication.Config, error)

取得儲存桶上目前的複寫設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

replication

replication.Config

從伺服器返回的複寫設定

err

error

標準錯誤

範例

replication, err := minioClient.GetBucketReplication(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

RemoveBucketReplication(ctx context.Context, bucketname string) error

移除儲存桶上的複寫設定。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

err

error

標準錯誤

範例

err = minioClient.RemoveBucketReplication(context.Background(), "my-bucketname")
if err != nil {
    fmt.Println(err)
    return
}

GetBucketReplicationMetrics(ctx context.Context, bucketName string) (replication.Metrics, error)

取得儲存桶上最新的複寫指標。這是 MinIO 特有的擴充功能。

參數

參數

類型

說明

ctx

context.Context

用於呼叫逾時/取消的自訂上下文

bucketName

string

儲存桶的名稱

傳回值

參數

類型

說明

metrics

replication.Metrics

從伺服器返回的複寫指標

err

error

標準錯誤

範例

replMetrics, err := minioClient.GetBucketReplicationMetrics(context.Background(), "my-bucketname")
if err != nil {
    log.Fatalln(err)
}

6. 用戶端自訂設定

SetAppInfo(appName, appVersion string)

將自訂應用程式詳細資訊新增至 User-Agent。

參數

參數

類型

說明

appName

string

執行 API 請求的應用程式名稱。

appVersion

string

執行 API 請求的應用程式版本。

範例

// Set Application name and version to be used in subsequent API requests.
minioClient.SetAppInfo("myCloudApp", "1.0.0")

TraceOn(outputStream io.Writer)

啟用 HTTP 追蹤。追蹤會寫入提供的 io.Writer。如果 outputStream 為 nil,追蹤會寫入 os.Stdout。

參數

參數

類型

說明

outputStream

io.Writer

HTTP 追蹤會寫入 outputStream。

TraceOff()

停用 HTTP 追蹤。

SetS3TransferAccelerate(acceleratedEndpoint string)

為之後的所有 API 請求設定 AWS S3 傳輸加速端點。注意:此 API 僅適用於 AWS S3,對於 S3 相容的物件儲存服務而言,不會執行任何操作。

參數

參數

類型

說明

acceleratedEndpoint

string

設定為新的 S3 傳輸加速端點。