minio

package module
v7.0.93 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 9, 2025 License: Apache-2.0 Imports: 64 Imported by: 2,846

README

MinIO Go Client SDK for Amazon S3 Compatible Cloud Storage Slack Sourcegraph Apache V2 License

The MinIO Go Client SDK provides straightforward APIs to access any Amazon S3 compatible object storage.

This Quickstart Guide covers how to install the MinIO client SDK, connect to MinIO, and create a sample file uploader. For a complete list of APIs and examples, see the godoc documentation or Go Client API Reference.

These examples presume a working Go development environment and the MinIO mc command line tool.

Download from Github

From your project directory:

go get github.com/minio/minio-go/v7

Initialize a MinIO Client Object

The MinIO client requires the following parameters to connect to an Amazon S3 compatible object storage:

Parameter Description
endpoint URL to object storage service.
_minio.Options_ All the options such as credentials, custom transport etc.
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 set up
}

Example - File Uploader

This sample code connects to an object storage server, creates a bucket, and uploads a file to the bucket. It uses the MinIO play server, a public MinIO cluster located at https://play.min.io.

The play server runs the latest stable version of MinIO and may be used for testing and development. The access credentials shown in this example are open to the public and all data uploaded to play should be considered public and non-protected.

FileUploader.go

This example does the following:

  • Connects to the MinIO play server using the provided credentials.
  • Creates a bucket named testbucket.
  • Uploads a file named testdata from /tmp.
  • Verifies the file was created using mc ls.
// FileUploader.go MinIO example
package main

import (
	"context"
	"log"

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

func main() {
	ctx := context.Background()
	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)
	}

	// Make a new bucket called testbucket.
	bucketName := "testbucket"
	location := "us-east-1"

	err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
	if err != nil {
		// Check to see if we already own this bucket (which happens if you run this twice)
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			log.Printf("We already own %s\n", bucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created %s\n", bucketName)
	}

	// Upload the test file
	// Change the value of filePath if the file is in another location
	objectName := "testdata"
	filePath := "/tmp/testdata"
	contentType := "application/octet-stream"

	// Upload the test file with FPutObject
	info, err := minioClient.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("Successfully uploaded %s of size %d\n", objectName, info.Size)
}

1. Create a test file containing data:

You can do this with dd on Linux or macOS systems:

dd if=/dev/urandom of=/tmp/testdata bs=2048 count=10

or fsutil on Windows:

fsutil file createnew "C:\Users\<username>\Desktop\sample.txt" 20480

2. Run FileUploader with the following commands:

go mod init example/FileUploader
go get github.com/minio/minio-go/v7
go get github.com/minio/minio-go/v7/pkg/credentials
go run FileUploader.go

The output resembles the following:

2023/11/01 14:27:55 Successfully created testbucket
2023/11/01 14:27:55 Successfully uploaded testdata of size 20480

3. Verify the Uploaded File With mc ls:

mc ls play/testbucket
[2023-11-01 14:27:55 UTC]  20KiB STANDARD TestDataFile

API Reference

The full API Reference is available here.

API Reference : Bucket Operations
API Reference : Bucket policy Operations
API Reference : Bucket notification Operations
API Reference : File Object Operations
API Reference : Object Operations
API Reference : Presigned Operations
API Reference : Client custom settings

Full Examples

Full Examples : Bucket Operations
Full Examples : Bucket policy Operations
Full Examples : Bucket lifecycle Operations
Full Examples : Bucket encryption Operations
Full Examples : Bucket replication Operations
Full Examples : Bucket notification Operations
Full Examples : File Object Operations
Full Examples : Object Operations
Full Examples : Encrypted Object Operations
Full Examples : Presigned Operations

Explore Further

Contribute

Contributors Guide

License

This SDK is distributed under the Apache License, Version 2.0, see LICENSE and NOTICE for more information.

Documentation

Index

Constants

View Source
const (
	Enabled = "Enabled"
	// Disabled  State = "Disabled" only used by MFA Delete not supported yet.
	Suspended = "Suspended"
)

Various supported states

View Source
const (
	// TierStandard is the standard retrieval tier
	TierStandard = TierType("Standard")
	// TierBulk is the bulk retrieval tier
	TierBulk = TierType("Bulk")
	// TierExpedited is the expedited retrieval tier
	TierExpedited = TierType("Expedited")
)
View Source
const (
	// GetObjectAttributesTags are tags used to defined
	// return values for the GetObjectAttributes API
	GetObjectAttributesTags = "ETag,Checksum,StorageClass,ObjectSize,ObjectParts"
	// GetObjectAttributesMaxParts defined the default maximum
	// number of parts returned by GetObjectAttributes
	GetObjectAttributesMaxParts = 1000
)
View Source
const (
	NoSuchBucket                      = "NoSuchBucket"
	NoSuchKey                         = "NoSuchKey"
	NoSuchUpload                      = "NoSuchUpload"
	AccessDenied                      = "AccessDenied"
	Conflict                          = "Conflict"
	PreconditionFailed                = "PreconditionFailed"
	InvalidArgument                   = "InvalidArgument"
	EntityTooLarge                    = "EntityTooLarge"
	EntityTooSmall                    = "EntityTooSmall"
	UnexpectedEOF                     = "UnexpectedEOF"
	APINotSupported                   = "APINotSupported"
	InvalidRegion                     = "InvalidRegion"
	NoSuchBucketPolicy                = "NoSuchBucketPolicy"
	BadDigest                         = "BadDigest"
	IncompleteBody                    = "IncompleteBody"
	InternalError                     = "InternalError"
	InvalidAccessKeyID                = "InvalidAccessKeyId"
	InvalidBucketName                 = "InvalidBucketName"
	InvalidDigest                     = "InvalidDigest"
	InvalidRange                      = "InvalidRange"
	MalformedXML                      = "MalformedXML"
	MissingContentLength              = "MissingContentLength"
	MissingContentMD5                 = "MissingContentMD5"
	MissingRequestBodyError           = "MissingRequestBodyError"
	NotImplemented                    = "NotImplemented"
	RequestTimeTooSkewed              = "RequestTimeTooSkewed"
	SignatureDoesNotMatch             = "SignatureDoesNotMatch"
	MethodNotAllowed                  = "MethodNotAllowed"
	InvalidPart                       = "InvalidPart"
	InvalidPartOrder                  = "InvalidPartOrder"
	InvalidObjectState                = "InvalidObjectState"
	AuthorizationHeaderMalformed      = "AuthorizationHeaderMalformed"
	MalformedPOSTRequest              = "MalformedPOSTRequest"
	BucketNotEmpty                    = "BucketNotEmpty"
	AllAccessDisabled                 = "AllAccessDisabled"
	MalformedPolicy                   = "MalformedPolicy"
	MissingFields                     = "MissingFields"
	AuthorizationQueryParametersError = "AuthorizationQueryParametersError"
	MalformedDate                     = "MalformedDate"
	BucketAlreadyOwnedByYou           = "BucketAlreadyOwnedByYou"
	InvalidDuration                   = "InvalidDuration"
	XAmzContentSHA256Mismatch         = "XAmzContentSHA256Mismatch"
	XMinioInvalidObjectName           = "XMinioInvalidObjectName"
	NoSuchCORSConfiguration           = "NoSuchCORSConfiguration"
	BucketAlreadyExists               = "BucketAlreadyExists"
	NoSuchVersion                     = "NoSuchVersion"
	NoSuchTagSet                      = "NoSuchTagSet"
	Testing                           = "Testing"
	Success                           = "Success"
)

Constants for error keys

View Source
const (

	// ETag is a common response header
	ETag = "ETag"
)
View Source
const MaxJitter = 1.0

MaxJitter will randomize over the full exponential backoff time

View Source
const NoJitter = 0.0

NoJitter disables the use of jitter for randomizing the exponential backoff time

View Source
const (
	// RestoreSelect represents the restore SELECT operation
	RestoreSelect = RestoreType("SELECT")
)

Variables

View Source
var DefaultRetryCap = time.Second

DefaultRetryCap - Each retry attempt never waits no longer than this maximum time duration.

View Source
var DefaultRetryUnit = 200 * time.Millisecond

DefaultRetryUnit - default unit multiplicative per retry. defaults to 200 * time.Millisecond

View Source
var DefaultTransport = func(secure bool) (*http.Transport, error) {
	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		MaxIdleConns:          256,
		MaxIdleConnsPerHost:   16,
		ResponseHeaderTimeout: time.Minute,
		IdleConnTimeout:       time.Minute,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 10 * time.Second,

		DisableCompression: true,
	}

	if secure {
		tr.TLSClientConfig = &tls.Config{

			MinVersion: tls.VersionTLS12,
		}
		if f := os.Getenv("SSL_CERT_FILE"); f != "" {
			rootCAs := mustGetSystemCertPool()
			data, err := os.ReadFile(f)
			if err == nil {
				rootCAs.AppendCertsFromPEM(data)
			}
			tr.TLSClientConfig.RootCAs = rootCAs
		}
	}
	return tr, nil
}

DefaultTransport - this default transport is similar to http.DefaultTransport but with additional param DisableCompression is set to true to avoid decompressing content with 'gzip' encoding.

View Source
var MaxRetry = 10

MaxRetry is the maximum number of retries before stopping.

Functions

func IsNetworkOrHostDown added in v7.0.14

func IsNetworkOrHostDown(err error, expectTimeouts bool) bool

IsNetworkOrHostDown - if there was a network error or if the host is down. expectTimeouts indicates that *context* timeouts are expected and does not indicate a downed host. Other timeouts still returns down.

func OptimalPartInfo added in v7.0.11

func OptimalPartInfo(objectSize int64, configuredPartSize uint64) (totalPartsCount int, partSize, lastPartSize int64, err error)

OptimalPartInfo - calculate the optimal part info for a given object size.

NOTE: Assumption here is that for any object to be uploaded to any S3 compatible object storage it will have the following parameters as constants.

maxPartsCount - 10000
minPartSize - 16MiB
maxMultipartPutObjectSize - 5TiB

Types

type AccessControlList added in v7.0.14

type AccessControlList struct {
	XMLName    xml.Name `xml:"AccessControlList"`
	Grant      []Grant
	Permission string `xml:"Permission"`
}

AccessControlList contains the set of grantees and the permissions assigned to each grantee.

type AdvancedGetOptions added in v7.0.6

type AdvancedGetOptions struct {
	ReplicationDeleteMarker           bool
	IsReplicationReadyForDeleteMarker bool
	ReplicationProxyRequest           string
}

AdvancedGetOptions for internal use by MinIO server - not intended for client use.

type AdvancedObjectTaggingOptions added in v7.0.66

type AdvancedObjectTaggingOptions struct {
	ReplicationProxyRequest string
}

AdvancedObjectTaggingOptions for internal use by MinIO server - not intended for client use.

type AdvancedPutOptions added in v7.0.6

type AdvancedPutOptions struct {
	SourceVersionID          string
	SourceETag               string
	ReplicationStatus        ReplicationStatus
	SourceMTime              time.Time
	ReplicationRequest       bool
	RetentionTimestamp       time.Time
	TaggingTimestamp         time.Time
	LegalholdTimestamp       time.Time
	ReplicationValidityCheck bool
}

AdvancedPutOptions for internal use - to be utilized by replication, ILM transition implementation on MinIO server

type AdvancedRemoveOptions added in v7.0.6

type AdvancedRemoveOptions struct {
	ReplicationDeleteMarker  bool
	ReplicationStatus        ReplicationStatus
	ReplicationMTime         time.Time
	ReplicationRequest       bool
	ReplicationValidityCheck bool // check permissions
}

AdvancedRemoveOptions intended for internal use by replication

type AppendObjectOptions added in v7.0.90

type AppendObjectOptions struct {
	// Provide a progress reader to indicate the current append() progress.
	Progress io.Reader
	// ChunkSize indicates the maximum append() size,
	// it is useful when you want to control how much data
	// per append() you are interested in sending to server
	// while keeping the input io.Reader of a longer length.
	ChunkSize uint64
	// Aggressively disable sha256 payload, it is automatically
	// turned-off for TLS supporting endpoints, useful in benchmarks
	// where you are interested in the peak() numbers.
	DisableContentSha256 bool
	// contains filtered or unexported fields
}

AppendObjectOptions https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-objects-append.html

func (AppendObjectOptions) Header added in v7.0.90

func (opts AppendObjectOptions) Header() (header http.Header)

Header returns the custom header for AppendObject API

type BucketInfo

type BucketInfo struct {
	// The name of the bucket.
	Name string `json:"name"`
	// Date the bucket was created.
	CreationDate time.Time `json:"creationDate"`
	// BucketRegion region where the bucket is present
	BucketRegion string `json:"bucketRegion"`
}

BucketInfo container for bucket metadata.

type BucketLookupType

type BucketLookupType int

BucketLookupType is type of url lookup supported by server.

const (
	BucketLookupAuto BucketLookupType = iota
	BucketLookupDNS
	BucketLookupPath
)

Different types of url lookup supported by the server.Initialized to BucketLookupAuto

type BucketOptions deprecated added in v7.0.13

type BucketOptions = RemoveBucketOptions

Deprecated: BucketOptions will be renamed to RemoveBucketOptions in future versions.

type BucketVersioningConfiguration

type BucketVersioningConfiguration struct {
	XMLName   xml.Name `xml:"VersioningConfiguration"`
	Status    string   `xml:"Status"`
	MFADelete string   `xml:"MfaDelete,omitempty"`
	// MinIO extension - allows selective, prefix-level versioning exclusion.
	// Requires versioning to be enabled
	ExcludedPrefixes []ExcludedPrefix `xml:",omitempty"`
	ExcludeFolders   bool             `xml:",omitempty"`
	PurgeOnDelete    string           `xml:",omitempty"`
}

BucketVersioningConfiguration is the versioning configuration structure

func (BucketVersioningConfiguration) Enabled added in v7.0.6

func (b BucketVersioningConfiguration) Enabled() bool

Enabled returns true if bucket versioning is enabled

func (BucketVersioningConfiguration) Suspended added in v7.0.6

func (b BucketVersioningConfiguration) Suspended() bool

Suspended returns true if bucket versioning is suspended

type CSVFileHeaderInfo

type CSVFileHeaderInfo string

CSVFileHeaderInfo - is the parameter for whether to utilize headers.

const (
	CSVFileHeaderInfoNone   CSVFileHeaderInfo = "NONE"
	CSVFileHeaderInfoIgnore CSVFileHeaderInfo = "IGNORE"
	CSVFileHeaderInfoUse    CSVFileHeaderInfo = "USE"
)

Constants for file header info.

type CSVInputOptions

type CSVInputOptions struct {
	FileHeaderInfo CSVFileHeaderInfo

	RecordDelimiter string

	FieldDelimiter string

	QuoteCharacter string

	QuoteEscapeCharacter string

	Comments string
	// contains filtered or unexported fields
}

CSVInputOptions csv input specific options

func (CSVInputOptions) MarshalXML

func (c CSVInputOptions) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML - produces the xml representation of the CSV input options struct

func (*CSVInputOptions) SetComments

func (c *CSVInputOptions) SetComments(val string)

SetComments sets the comments character in the CSV input options

func (*CSVInputOptions) SetFieldDelimiter

func (c *CSVInputOptions) SetFieldDelimiter(val string)

SetFieldDelimiter sets the field delimiter in the CSV input options

func (*CSVInputOptions) SetFileHeaderInfo

func (c *CSVInputOptions) SetFileHeaderInfo(val CSVFileHeaderInfo)

SetFileHeaderInfo sets the file header info in the CSV input options

func (*CSVInputOptions) SetQuoteCharacter

func (c *CSVInputOptions) SetQuoteCharacter(val string)

SetQuoteCharacter sets the quote character in the CSV input options

func (*CSVInputOptions) SetQuoteEscapeCharacter

func (c *CSVInputOptions) SetQuoteEscapeCharacter(val string)

SetQuoteEscapeCharacter sets the quote escape character in the CSV input options

func (*CSVInputOptions) SetRecordDelimiter

func (c *CSVInputOptions) SetRecordDelimiter(val string)

SetRecordDelimiter sets the record delimiter in the CSV input options

type CSVOutputOptions

type CSVOutputOptions struct {
	QuoteFields CSVQuoteFields

	RecordDelimiter string

	FieldDelimiter string

	QuoteCharacter string

	QuoteEscapeCharacter string
	// contains filtered or unexported fields
}

CSVOutputOptions csv output specific options

func (CSVOutputOptions) MarshalXML

func (c CSVOutputOptions) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML - produces the xml representation of the CSVOutputOptions struct

func (*CSVOutputOptions) SetFieldDelimiter

func (c *CSVOutputOptions) SetFieldDelimiter(val string)

SetFieldDelimiter sets the field delimiter character in the CSV output options

func (*CSVOutputOptions) SetQuoteCharacter

func (c *CSVOutputOptions) SetQuoteCharacter(val string)

SetQuoteCharacter sets the quote character in the CSV output options

func (*CSVOutputOptions) SetQuoteEscapeCharacter

func (c *CSVOutputOptions) SetQuoteEscapeCharacter(val string)

SetQuoteEscapeCharacter sets the quote escape character in the CSV output options

func (*CSVOutputOptions) SetQuoteFields

func (c *CSVOutputOptions) SetQuoteFields(val CSVQuoteFields)

SetQuoteFields sets the quote field parameter in the CSV output options

func (*CSVOutputOptions) SetRecordDelimiter

func (c *CSVOutputOptions) SetRecordDelimiter(val string)

SetRecordDelimiter sets the record delimiter character in the CSV output options

type CSVQuoteFields

type CSVQuoteFields string

CSVQuoteFields - is the parameter for how CSV fields are quoted.

const (
	CSVQuoteFieldsAlways   CSVQuoteFields = "Always"
	CSVQuoteFieldsAsNeeded CSVQuoteFields = "AsNeeded"
)

Constants for csv quote styles.

type Checksum added in v7.0.55

type Checksum struct {
	Type ChecksumType
	// contains filtered or unexported fields
}

Checksum is a type and encoded value.

func NewChecksum added in v7.0.55

func NewChecksum(t ChecksumType, b []byte) Checksum

NewChecksum sets the checksum to the value of b, which is the raw hash output. If the length of c does not match t.RawByteLen, a checksum with ChecksumNone is returned.

func NewChecksumString added in v7.0.55

func NewChecksumString(t ChecksumType, s string) Checksum

NewChecksumString sets the checksum to the value of s, which is the base 64 encoded raw hash output. If the length of c does not match t.RawByteLen, it is not added.

func (Checksum) Encoded added in v7.0.55

func (c Checksum) Encoded() string

Encoded returns the encoded value. Returns the empty string if not set or valid.

func (Checksum) IsSet added in v7.0.55

func (c Checksum) IsSet() bool

IsSet returns whether the checksum is valid and known.

func (Checksum) Raw added in v7.0.55

func (c Checksum) Raw() []byte

Raw returns the raw checksum value if set.

type ChecksumMode added in v7.0.90

type ChecksumMode uint32

ChecksumMode contains information about the checksum mode on the object

const (
	// ChecksumFullObjectMode Full object checksum `csumCombine(csum1, csum2...)...), csumN...)`
	ChecksumFullObjectMode ChecksumMode = 1 << iota

	// ChecksumCompositeMode Composite checksum `csum([csum1 + csum2 ... + csumN])`
	ChecksumCompositeMode
)

func (ChecksumMode) Is added in v7.0.90

func (c ChecksumMode) Is(t ChecksumMode) bool

Is returns if c is all of t.

func (ChecksumMode) Key added in v7.0.90

func (c ChecksumMode) Key() string

Key returns the header key.

func (ChecksumMode) String added in v7.0.90

func (c ChecksumMode) String() string

type ChecksumType added in v7.0.55

type ChecksumType uint32

ChecksumType contains information about the checksum type.

const (

	// ChecksumSHA256 indicates a SHA256 checksum.
	ChecksumSHA256 ChecksumType = 1 << iota
	// ChecksumSHA1 indicates a SHA-1 checksum.
	ChecksumSHA1
	// ChecksumCRC32 indicates a CRC32 checksum with IEEE table.
	ChecksumCRC32
	// ChecksumCRC32C indicates a CRC32 checksum with Castagnoli table.
	ChecksumCRC32C
	// ChecksumCRC64NVME indicates CRC64 with 0xad93d23594c93659 polynomial.
	ChecksumCRC64NVME

	// ChecksumFullObject is a modifier that can be used on CRC32 and CRC32C
	// to indicate full object checksums.
	ChecksumFullObject

	// ChecksumNone indicates no checksum.
	ChecksumNone ChecksumType = 0

	// ChecksumFullObjectCRC32 indicates full object CRC32
	ChecksumFullObjectCRC32 = ChecksumCRC32 | ChecksumFullObject

	// ChecksumFullObjectCRC32C indicates full object CRC32C
	ChecksumFullObjectCRC32C = ChecksumCRC32C | ChecksumFullObject
)

func (ChecksumType) Base added in v7.0.82

func (c ChecksumType) Base() ChecksumType

Base returns the base type, without modifiers.

func (ChecksumType) CanComposite added in v7.0.82

func (c ChecksumType) CanComposite() bool

CanComposite will return if the checksum type can be used for composite multipart upload on AWS.

func (ChecksumType) CanMergeCRC added in v7.0.82

func (c ChecksumType) CanMergeCRC() bool

CanMergeCRC will return if the checksum type can be used for multipart upload on AWS.

func (ChecksumType) ChecksumBytes added in v7.0.55

func (c ChecksumType) ChecksumBytes(b []byte) Checksum

ChecksumBytes returns a checksum of the content b with type c.

func (ChecksumType) ChecksumReader added in v7.0.55

func (c ChecksumType) ChecksumReader(r io.Reader) (Checksum, error)

ChecksumReader reads all of r and returns a checksum of type c. Returns any error that may have occurred while reading.

func (ChecksumType) CompositeChecksum added in v7.0.82

func (c ChecksumType) CompositeChecksum(p []ObjectPart) (*Checksum, error)

CompositeChecksum returns the composite checksum of all provided parts.

func (ChecksumType) EncodeToString added in v7.0.82

func (c ChecksumType) EncodeToString(b []byte) string

EncodeToString the encoded hash value of the content provided in b.

func (ChecksumType) FullObjectChecksum added in v7.0.82

func (c ChecksumType) FullObjectChecksum(p []ObjectPart) (*Checksum, error)

FullObjectChecksum will return the full object checksum from provided parts.

func (ChecksumType) FullObjectRequested added in v7.0.82

func (c ChecksumType) FullObjectRequested() bool

FullObjectRequested will return if the checksum type indicates full object checksum was requested.

func (ChecksumType) Hasher added in v7.0.55

func (c ChecksumType) Hasher() hash.Hash

Hasher returns a hasher corresponding to the checksum type. Returns nil if no checksum.

func (ChecksumType) Is added in v7.0.55

func (c ChecksumType) Is(t ChecksumType) bool

Is returns if c is all of t.

func (ChecksumType) IsSet added in v7.0.55

func (c ChecksumType) IsSet() bool

IsSet returns whether the type is valid and known.

func (ChecksumType) Key added in v7.0.55

func (c ChecksumType) Key() string

Key returns the header key. returns empty string if invalid or none.

func (ChecksumType) KeyCapitalized added in v7.0.76

func (c ChecksumType) KeyCapitalized() string

KeyCapitalized returns the capitalized key as used in HTTP headers.

func (ChecksumType) RawByteLen added in v7.0.55

func (c ChecksumType) RawByteLen() int

RawByteLen returns the size of the un-encoded checksum.

func (*ChecksumType) SetDefault added in v7.0.76

func (c *ChecksumType) SetDefault(t ChecksumType)

SetDefault will set the checksum if not already set.

func (ChecksumType) String added in v7.0.55

func (c ChecksumType) String() string

String returns the type as a string. CRC32, CRC32C, SHA1, and SHA256 for valid values. Empty string for unset and "<invalid>" if not valid.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client implements Amazon S3 compatible methods.

func New

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

New - instantiate minio client with options

func (*Client) AppendObject added in v7.0.90

func (c *Client) AppendObject(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,
	opts AppendObjectOptions,
) (info UploadInfo, err error)

AppendObject - S3 Express Zone https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-objects-append.html

func (*Client) BucketExists

func (c *Client) BucketExists(ctx context.Context, bucketName string) (bool, error)

BucketExists verifies if bucket exists and you have permission to access it. Allows for a Context to control cancellations and timeouts.

func (*Client) CancelBucketReplicationResync added in v7.0.92

func (c *Client) CancelBucketReplicationResync(ctx context.Context, bucketName string, tgtArn string) (id string, err error)

CancelBucketReplicationResync cancels in progress replication resync

func (*Client) CheckBucketReplication added in v7.0.59

func (c *Client) CheckBucketReplication(ctx context.Context, bucketName string) (err error)

CheckBucketReplication validates if replication is set up properly for a bucket

func (*Client) ComposeObject

func (c *Client) ComposeObject(ctx context.Context, dst CopyDestOptions, srcs ...CopySrcOptions) (UploadInfo, error)

ComposeObject - creates an object using server-side copying of existing objects. It takes a list of source objects (with optional offsets) and concatenates them into a new object using only server-side copying operations. Optionally takes progress reader hook for applications to look at current progress.

func (*Client) CopyObject

func (c *Client) CopyObject(ctx context.Context, dst CopyDestOptions, src CopySrcOptions) (UploadInfo, error)

CopyObject - copy a source object into a new object

func (*Client) CreateSession added in v7.0.92

func (c *Client) CreateSession(ctx context.Context, bucketName string, sessionMode SessionMode) (cred credentials.Value, err error)

CreateSession - https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateSession.html the returning credentials may be cached depending on the expiration of the original credential, credentials will get renewed 10 secs earlier than when its gonna expire allowing for some leeway in the renewal process.

func (*Client) CredContext added in v7.0.83

func (c *Client) CredContext() *credentials.CredContext

CredContext returns the context for fetching credentials

func (*Client) EnableVersioning

func (c *Client) EnableVersioning(ctx context.Context, bucketName string) error

EnableVersioning - enable object versioning in given bucket.

func (*Client) EndpointURL

func (c *Client) EndpointURL() *url.URL

EndpointURL returns the URL of the S3 endpoint.

func (*Client) FGetObject

func (c *Client) FGetObject(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error

FGetObject - download contents of an object to a local file. The options can be used to specify the GET request further.

func (*Client) FPutObject

func (c *Client) FPutObject(ctx context.Context, bucketName, objectName, filePath string, opts PutObjectOptions) (info UploadInfo, err error)

FPutObject - Create an object in a bucket, with contents from file at filePath. Allows request cancellation.

func (*Client) GetBucketCors added in v7.0.75

func (c *Client) GetBucketCors(ctx context.Context, bucketName string) (*cors.Config, error)

GetBucketCors returns the current cors

func (*Client) GetBucketEncryption

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

GetBucketEncryption gets the default encryption configuration on an existing bucket with a context to control cancellations and timeouts.

func (*Client) GetBucketLifecycle

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

GetBucketLifecycle fetch bucket lifecycle configuration

func (*Client) GetBucketLifecycleWithInfo added in v7.0.55

func (c *Client) GetBucketLifecycleWithInfo(ctx context.Context, bucketName string) (*lifecycle.Configuration, time.Time, error)

GetBucketLifecycleWithInfo fetch bucket lifecycle configuration along with when it was last updated

func (*Client) GetBucketLocation

func (c *Client) GetBucketLocation(ctx context.Context, bucketName string) (string, error)

GetBucketLocation - get location for the bucket name from location cache, if not fetch freshly by making a new request.

func (*Client) GetBucketNotification

func (c *Client) GetBucketNotification(ctx context.Context, bucketName string) (bucketNotification notification.Configuration, err error)

GetBucketNotification returns current bucket notification configuration

func (*Client) GetBucketObjectLockConfig

func (c *Client) GetBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *RetentionMode, validity *uint, unit *ValidityUnit, err error)

GetBucketObjectLockConfig gets object lock configuration of given bucket.

func (*Client) GetBucketPolicy

func (c *Client) GetBucketPolicy(ctx context.Context, bucketName string) (string, error)

GetBucketPolicy returns the current policy

func (*Client) GetBucketReplication

func (c *Client) GetBucketReplication(ctx context.Context, bucketName string) (cfg replication.Config, err error)

GetBucketReplication fetches bucket replication configuration.If config is not found, returns empty config with nil error.

func (*Client) GetBucketReplicationMetrics added in v7.0.11

func (c *Client) GetBucketReplicationMetrics(ctx context.Context, bucketName string) (s replication.Metrics, err error)

GetBucketReplicationMetrics fetches bucket replication status metrics

func (*Client) GetBucketReplicationMetricsV2 added in v7.0.59

func (c *Client) GetBucketReplicationMetricsV2(ctx context.Context, bucketName string) (s replication.MetricsV2, err error)

GetBucketReplicationMetricsV2 fetches bucket replication status metrics

func (*Client) GetBucketReplicationResyncStatus added in v7.0.22

func (c *Client) GetBucketReplicationResyncStatus(ctx context.Context, bucketName, arn string) (rinfo replication.ResyncTargetsInfo, err error)

GetBucketReplicationResyncStatus gets the status of replication resync

func (*Client) GetBucketTagging

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

GetBucketTagging fetch tagging configuration for a bucket with a context to control cancellations and timeouts.

func (*Client) GetBucketVersioning

func (c *Client) GetBucketVersioning(ctx context.Context, bucketName string) (BucketVersioningConfiguration, error)

GetBucketVersioning gets the versioning configuration on an existing bucket with a context to control cancellations and timeouts.

func (*Client) GetCreds added in v7.0.90

func (c *Client) GetCreds() (credentials.Value, error)

GetCreds returns the access creds for the client

func (*Client) GetObject

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

GetObject wrapper function that accepts a request context

func (*Client) GetObjectACL

func (c *Client) GetObjectACL(ctx context.Context, bucketName, objectName string) (*ObjectInfo, error)

GetObjectACL get object ACLs

func (*Client) GetObjectAttributes added in v7.0.67

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

GetObjectAttributes API combines HeadObject and ListParts. More details on usage can be found in the documentation for ObjectAttributesOptions{}

func (*Client) GetObjectLegalHold

func (c *Client) GetObjectLegalHold(ctx context.Context, bucketName, objectName string, opts GetObjectLegalHoldOptions) (status *LegalHoldStatus, err error)

GetObjectLegalHold gets legal-hold status of given object.

func (*Client) GetObjectLockConfig

func (c *Client) GetObjectLockConfig(ctx context.Context, bucketName string) (objectLock string, mode *RetentionMode, validity *uint, unit *ValidityUnit, err error)

GetObjectLockConfig gets object lock configuration of given bucket.

func (*Client) GetObjectRetention

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

GetObjectRetention gets retention of given object.

func (*Client) GetObjectTagging

func (c *Client) GetObjectTagging(ctx context.Context, bucketName, objectName string, opts GetObjectTaggingOptions) (*tags.Tags, error)

GetObjectTagging fetches object tag(s) with options to target a specific object version in a versioned bucket.

func (*Client) HealthCheck added in v7.0.14

func (c *Client) HealthCheck(hcDuration time.Duration) (context.CancelFunc, error)

HealthCheck starts a healthcheck to see if endpoint is up. Returns a context cancellation function, to stop the health check, and an error if health check is already started.

func (*Client) IsOffline added in v7.0.14

func (c *Client) IsOffline() bool

IsOffline returns true if healthcheck enabled and client is offline If HealthCheck function has not been called this will always return false.

func (*Client) IsOnline added in v7.0.14

func (c *Client) IsOnline() bool

IsOnline returns true if healthcheck enabled and client is online. If HealthCheck function has not been called this will always return true.

func (*Client) ListBuckets

func (c *Client) ListBuckets(ctx context.Context) ([]BucketInfo, error)

ListBuckets list all buckets owned by this authenticated user.

This call requires explicit authentication, no anonymous requests are allowed for listing buckets.

api := client.New(....)
for message := range api.ListBuckets(context.Background()) {
    fmt.Println(message)
}

func (*Client) ListDirectoryBuckets added in v7.0.92

func (c *Client) ListDirectoryBuckets(ctx context.Context) (iter.Seq2[BucketInfo, error], error)

ListDirectoryBuckets list all buckets owned by this authenticated user.

This call requires explicit authentication, no anonymous requests are allowed for listing buckets.

api := client.New(....) dirBuckets, err := api.ListDirectoryBuckets(context.Background())

func (*Client) ListIncompleteUploads

func (c *Client) ListIncompleteUploads(ctx context.Context, bucketName, objectPrefix string, recursive bool) <-chan ObjectMultipartInfo

ListIncompleteUploads - List incompletely uploaded multipart objects.

ListIncompleteUploads lists all incompleted objects matching the objectPrefix from the specified bucket. If recursion is enabled it would list all subdirectories and all its contents.

Your input parameters are just bucketName, objectPrefix, recursive. If you enable recursive as 'true' this function will return back all the multipart objects in a given bucket name.

api := client.New(....)
// Recurively list all objects in 'mytestbucket'
recursive := true
for message := range api.ListIncompleteUploads(context.Background(), "mytestbucket", "starthere", recursive) {
    fmt.Println(message)
}

func (*Client) ListObjects

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

ListObjects returns objects list after evaluating the passed options.

api := client.New(....)
for object := range api.ListObjects(ctx, "mytestbucket", minio.ListObjectsOptions{Prefix: "starthere", Recursive:true}) {
    fmt.Println(object)
}

If caller cancels the context, then the last entry on the 'chan ObjectInfo' will be the context.Error() caller must drain the channel entirely and wait until channel is closed before proceeding, without waiting on the channel to be closed completely you might leak goroutines.

func (*Client) ListObjectsIter added in v7.0.92

func (c *Client) ListObjectsIter(ctx context.Context, bucketName string, opts ListObjectsOptions) iter.Seq[ObjectInfo]

ListObjectsIter returns object list as a iterator sequence. caller must cancel the context if they are not interested in iterating further, if no more entries the iterator will automatically stop.

api := client.New(....)
for object := range api.ListObjectsIter(ctx, "mytestbucket", minio.ListObjectsOptions{Prefix: "starthere", Recursive:true}) {
    if object.Err != nil {
        // handle the errors.
    }
    fmt.Println(object)
}

Canceling the context the iterator will stop, if you wish to discard the yielding make sure to cancel the passed context without that you might leak coroutines

func (*Client) ListenBucketNotification

func (c *Client) ListenBucketNotification(ctx context.Context, bucketName, prefix, suffix string, events []string) <-chan notification.Info

ListenBucketNotification listen for bucket events, this is a MinIO specific API

func (*Client) ListenNotification added in v7.0.2

func (c *Client) ListenNotification(ctx context.Context, prefix, suffix string, events []string) <-chan notification.Info

ListenNotification listen for all events, this is a MinIO specific API

func (*Client) MakeBucket

func (c *Client) MakeBucket(ctx context.Context, bucketName string, opts MakeBucketOptions) (err error)

MakeBucket creates a new bucket with bucketName with a context to control cancellations and timeouts.

Location is an optional argument, by default all buckets are created in US Standard Region.

For Amazon S3 for more supported regions - http://docs.aws.amazon.com/general/latest/gr/rande.html For Google Cloud Storage for more supported regions - https://cloud.google.com/storage/docs/bucket-locations

func (*Client) Presign

func (c *Client) Presign(ctx context.Context, method, bucketName, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error)

Presign - returns a presigned URL for any http method of your choice along with custom request params and extra signed headers. URL can have a maximum expiry of upto 7days or a minimum of 1sec.

func (*Client) PresignHeader added in v7.0.16

func (c *Client) PresignHeader(ctx context.Context, method, bucketName, objectName string, expires time.Duration, reqParams url.Values, extraHeaders http.Header) (u *url.URL, err error)

PresignHeader - similar to Presign() but allows including HTTP headers that will be used to build the signature. The request using the resulting URL will need to have the exact same headers to be added for signature validation to pass.

FIXME: The extra header parameter should be included in Presign() in the next major version bump, and this function should then be deprecated.

func (*Client) PresignedGetObject

func (c *Client) PresignedGetObject(ctx context.Context, bucketName, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error)

PresignedGetObject - Returns a presigned URL to access an object data without credentials. URL can have a maximum expiry of upto 7days or a minimum of 1sec. Additionally you can override a set of response headers using the query parameters.

func (*Client) PresignedHeadObject

func (c *Client) PresignedHeadObject(ctx context.Context, bucketName, objectName string, expires time.Duration, reqParams url.Values) (u *url.URL, err error)

PresignedHeadObject - Returns a presigned URL to access object metadata without credentials. URL can have a maximum expiry of upto 7days or a minimum of 1sec. Additionally you can override a set of response headers using the query parameters.

func (*Client) PresignedPostPolicy

func (c *Client) PresignedPostPolicy(ctx context.Context, p *PostPolicy) (u *url.URL, formData map[string]string, err error)

PresignedPostPolicy - Returns POST urlString, form data to upload an object.

func (*Client) PresignedPutObject

func (c *Client) PresignedPutObject(ctx context.Context, bucketName, objectName string, expires time.Duration) (u *url.URL, err error)

PresignedPutObject - Returns a presigned URL to upload an object without credentials. URL can have a maximum expiry of upto 7days or a minimum of 1sec.

func (*Client) PromptObject added in v7.0.81

func (c *Client) PromptObject(ctx context.Context, bucketName, objectName, prompt string, opts PromptObjectOptions) (io.ReadCloser, error)

PromptObject performs language model inference with the prompt and referenced object as context. Inference is performed using a Lambda handler that can process the prompt and object. Currently, this functionality is limited to certain MinIO servers.

func (*Client) PutObject

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

PutObject creates an object in a bucket.

You must have WRITE permissions on a bucket to create an object.

  • For size smaller than 16MiB PutObject automatically does a single atomic PUT operation.

  • For size larger than 16MiB PutObject automatically does a multipart upload operation.

  • For size input as -1 PutObject does a multipart Put operation until input stream reaches EOF. Maximum object size that can be uploaded through this operation will be 5TiB.

    WARNING: Passing down '-1' will use memory and these cannot be reused for best outcomes for PutObject(), pass the size always.

NOTE: Upon errors during upload multipart operation is entirely aborted.

func (*Client) PutObjectFanOut added in v7.0.53

func (c *Client) PutObjectFanOut(ctx context.Context, bucket string, fanOutData io.Reader, fanOutReq PutObjectFanOutRequest) ([]PutObjectFanOutResponse, error)

PutObjectFanOut - is a variant of PutObject instead of writing a single object from a single stream multiple objects are written, defined via a list of PutObjectFanOutRequests. Each entry in PutObjectFanOutRequest carries an object keyname and its relevant metadata if any. `Key` is mandatory, rest of the other options in PutObjectFanOutRequest are optional.

func (*Client) PutObjectLegalHold

func (c *Client) PutObjectLegalHold(ctx context.Context, bucketName, objectName string, opts PutObjectLegalHoldOptions) error

PutObjectLegalHold : sets object legal hold for a given object and versionID.

func (*Client) PutObjectRetention

func (c *Client) PutObjectRetention(ctx context.Context, bucketName, objectName string, opts PutObjectRetentionOptions) error

PutObjectRetention sets object retention for a given object and versionID.

func (*Client) PutObjectTagging

func (c *Client) PutObjectTagging(ctx context.Context, bucketName, objectName string, otags *tags.Tags, opts PutObjectTaggingOptions) error

PutObjectTagging replaces or creates object tag(s) and can target a specific object version in a versioned bucket.

func (*Client) PutObjectsSnowball added in v7.0.15

func (c *Client) PutObjectsSnowball(ctx context.Context, bucketName string, opts SnowballOptions, objs <-chan SnowballObject) (err error)

PutObjectsSnowball will put multiple objects with a single put call. A (compressed) TAR file will be created which will contain multiple objects. The key for each object will be used for the destination in the specified bucket. Total size should be < 5TB. This function blocks until 'objs' is closed and the content has been uploaded.

func (*Client) RemoveAllBucketNotification

func (c *Client) RemoveAllBucketNotification(ctx context.Context, bucketName string) error

RemoveAllBucketNotification - Remove bucket notification clears all previously specified config

func (*Client) RemoveBucket

func (c *Client) RemoveBucket(ctx context.Context, bucketName string) error

RemoveBucket deletes the bucket name.

All objects (including all object versions and delete markers).
in the bucket must be deleted before successfully attempting this request.

func (*Client) RemoveBucketEncryption

func (c *Client) RemoveBucketEncryption(ctx context.Context, bucketName string) error

RemoveBucketEncryption removes the default encryption configuration on a bucket with a context to control cancellations and timeouts.

func (*Client) RemoveBucketReplication

func (c *Client) RemoveBucketReplication(ctx context.Context, bucketName string) error

RemoveBucketReplication removes a replication config on an existing bucket.

func (*Client) RemoveBucketTagging

func (c *Client) RemoveBucketTagging(ctx context.Context, bucketName string) error

RemoveBucketTagging removes tagging configuration for a bucket with a context to control cancellations and timeouts.

func (*Client) RemoveBucketWithOptions added in v7.0.13

func (c *Client) RemoveBucketWithOptions(ctx context.Context, bucketName string, opts RemoveBucketOptions) error

RemoveBucketWithOptions deletes the bucket name.

All objects (including all object versions and delete markers) in the bucket will be deleted forcibly if bucket options set ForceDelete to 'true'.

func (*Client) RemoveIncompleteUpload

func (c *Client) RemoveIncompleteUpload(ctx context.Context, bucketName, objectName string) error

RemoveIncompleteUpload aborts an partially uploaded object.

func (*Client) RemoveObject

func (c *Client) RemoveObject(ctx context.Context, bucketName, objectName string, opts RemoveObjectOptions) error

RemoveObject removes an object from a bucket.

func (*Client) RemoveObjectTagging

func (c *Client) RemoveObjectTagging(ctx context.Context, bucketName, objectName string, opts RemoveObjectTaggingOptions) error

RemoveObjectTagging removes object tag(s) with options to control a specific object version in a versioned bucket

func (*Client) RemoveObjects

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

RemoveObjects removes multiple objects from a bucket while it is possible to specify objects versions which are received from objectsCh. Remove failures are sent back via error channel.

func (*Client) RemoveObjectsWithIter added in v7.0.93

func (c *Client) RemoveObjectsWithIter(ctx context.Context, bucketName string, objectsIter iter.Seq[ObjectInfo], opts RemoveObjectsOptions) (iter.Seq[RemoveObjectResult], error)

RemoveObjectsWithIter bulk deletes multiple objects from a bucket. Objects (with optional versions) to be removed must be provided with an iterator. Objects are removed asynchronously and results must be consumed. If the returned result iterator is stopped, the context is canceled, or a remote call failed, the provided iterator will no longer accept more objects.

func (*Client) RemoveObjectsWithResult added in v7.0.17

func (c *Client) RemoveObjectsWithResult(ctx context.Context, bucketName string, objectsCh <-chan ObjectInfo, opts RemoveObjectsOptions) <-chan RemoveObjectResult

RemoveObjectsWithResult removes multiple objects from a bucket while it is possible to specify objects versions which are received from objectsCh. Remove results, successes and failures are sent back via RemoveObjectResult channel

func (*Client) ResetBucketReplication added in v7.0.11

func (c *Client) ResetBucketReplication(ctx context.Context, bucketName string, olderThan time.Duration) (rID string, err error)

ResetBucketReplication kicks off replication of previously replicated objects if ExistingObjectReplication is enabled in the replication config

func (*Client) ResetBucketReplicationOnTarget added in v7.0.14

func (c *Client) ResetBucketReplicationOnTarget(ctx context.Context, bucketName string, olderThan time.Duration, tgtArn string) (replication.ResyncTargetsInfo, error)

ResetBucketReplicationOnTarget kicks off replication of previously replicated objects if ExistingObjectReplication is enabled in the replication config

func (*Client) RestoreObject added in v7.0.14

func (c *Client) RestoreObject(ctx context.Context, bucketName, objectName, versionID string, req RestoreRequest) error

RestoreObject is a implementation of https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html AWS S3 API

func (*Client) SelectObjectContent

func (c *Client) SelectObjectContent(ctx context.Context, bucketName, objectName string, opts SelectObjectOptions) (*SelectResults, error)

SelectObjectContent is a implementation of http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectSELECTContent.html AWS S3 API.

func (*Client) SetAppInfo

func (c *Client) SetAppInfo(appName, appVersion string)

SetAppInfo - add application details to user agent.

func (*Client) SetBucketCors added in v7.0.75

func (c *Client) SetBucketCors(ctx context.Context, bucketName string, corsConfig *cors.Config) error

SetBucketCors sets the cors configuration for the bucket

func (*Client) SetBucketEncryption

func (c *Client) SetBucketEncryption(ctx context.Context, bucketName string, config *sse.Configuration) error

SetBucketEncryption sets the default encryption configuration on an existing bucket.

func (*Client) SetBucketLifecycle

func (c *Client) SetBucketLifecycle(ctx context.Context, bucketName string, config *lifecycle.Configuration) error

SetBucketLifecycle set the lifecycle on an existing bucket.

func (*Client) SetBucketNotification

func (c *Client) SetBucketNotification(ctx context.Context, bucketName string, config notification.Configuration) error

SetBucketNotification saves a new bucket notification with a context to control cancellations and timeouts.

func (*Client) SetBucketObjectLockConfig

func (c *Client) SetBucketObjectLockConfig(ctx context.Context, bucketName string, mode *RetentionMode, validity *uint, unit *ValidityUnit) error

SetBucketObjectLockConfig sets object lock configuration in given bucket. mode, validity and unit are either all set or all nil.

func (*Client) SetBucketPolicy

func (c *Client) SetBucketPolicy(ctx context.Context, bucketName, policy string) error

SetBucketPolicy sets the access permissions on an existing bucket.

func (*Client) SetBucketReplication

func (c *Client) SetBucketReplication(ctx context.Context, bucketName string, cfg replication.Config) error

SetBucketReplication sets a replication config on an existing bucket.

func (*Client) SetBucketTagging

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

SetBucketTagging sets tagging configuration for a bucket with a context to control cancellations and timeouts.

func (*Client) SetBucketVersioning

func (c *Client) SetBucketVersioning(ctx context.Context, bucketName string, config BucketVersioningConfiguration) error

SetBucketVersioning sets a bucket versioning configuration

func (*Client) SetObjectLockConfig

func (c *Client) SetObjectLockConfig(ctx context.Context, bucketName string, mode *RetentionMode, validity *uint, unit *ValidityUnit) error

SetObjectLockConfig sets object lock configuration in given bucket. mode, validity and unit are either all set or all nil.

func (*Client) SetS3EnableDualstack added in v7.0.69

func (c *Client) SetS3EnableDualstack(enabled bool)

SetS3EnableDualstack turns s3 dual-stack endpoints on or off for all requests. The feature is only specific to S3 and is on by default. To read more about Amazon S3 dual-stack endpoints visit - https://docs.aws.amazon.com/AmazonS3/latest/userguide/dual-stack-endpoints.html

func (*Client) SetS3TransferAccelerate

func (c *Client) SetS3TransferAccelerate(accelerateEndpoint string)

SetS3TransferAccelerate - turns s3 accelerated endpoint on or off for all your requests. This feature is only specific to S3 for all other endpoints this function does nothing. To read further details on s3 transfer acceleration please vist - http://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html

func (*Client) StatObject

func (c *Client) StatObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error)

StatObject verifies if object exists, you have permission to access it and returns information about the object.

func (*Client) SuspendVersioning

func (c *Client) SuspendVersioning(ctx context.Context, bucketName string) error

SuspendVersioning - suspend object versioning in given bucket.

func (*Client) TraceErrorsOnlyOff

func (c *Client) TraceErrorsOnlyOff()

TraceErrorsOnlyOff - Turns off the errors only tracing and everything will be traced after this call. If all tracing needs to be turned off, call TraceOff().

func (*Client) TraceErrorsOnlyOn

func (c *Client) TraceErrorsOnlyOn(outputStream io.Writer)

TraceErrorsOnlyOn - same as TraceOn, but only errors will be traced.

func (*Client) TraceOff

func (c *Client) TraceOff()

TraceOff - disable HTTP tracing.

func (*Client) TraceOn

func (c *Client) TraceOn(outputStream io.Writer)

TraceOn - enable HTTP tracing.

type CommonPrefix

type CommonPrefix struct {
	Prefix string
}

CommonPrefix container for prefix response.

type CompletePart

type CompletePart struct {
	// Part number identifies the part.
	PartNumber int
	ETag       string

	// Checksum values
	ChecksumCRC32     string `xml:"ChecksumCRC32,omitempty"`
	ChecksumCRC32C    string `xml:"ChecksumCRC32C,omitempty"`
	ChecksumSHA1      string `xml:"ChecksumSHA1,omitempty"`
	ChecksumSHA256    string `xml:"ChecksumSHA256,omitempty"`
	ChecksumCRC64NVME string `xml:",omitempty"`
}

CompletePart sub container lists individual part numbers and their md5sum, part of completeMultipartUpload.

func (CompletePart) Checksum added in v7.0.76

func (c CompletePart) Checksum(t ChecksumType) string

Checksum will return the checksum for the given type. Will return the empty string if not set.

type CopyDestOptions

type CopyDestOptions struct {
	Bucket string // points to destination bucket
	Object string // points to destination object

	// `Encryption` is the key info for server-side-encryption with customer
	// provided key. If it is nil, no encryption is performed.
	Encryption encrypt.ServerSide

	// `userMeta` is the user-metadata key-value pairs to be set on the
	// destination. The keys are automatically prefixed with `x-amz-meta-`
	// if needed. If nil is passed, and if only a single source (of any
	// size) is provided in the ComposeObject call, then metadata from the
	// source is copied to the destination.
	// if no user-metadata is provided, it is copied from source
	// (when there is only once source object in the compose
	// request)
	UserMetadata map[string]string
	// UserMetadata is only set to destination if ReplaceMetadata is true
	// other value is UserMetadata is ignored and we preserve src.UserMetadata
	// NOTE: if you set this value to true and now metadata is present
	// in UserMetadata your destination object will not have any metadata
	// set.
	ReplaceMetadata bool

	// `userTags` is the user defined object tags to be set on destination.
	// This will be set only if the `replaceTags` field is set to true.
	// Otherwise this field is ignored
	UserTags    map[string]string
	ReplaceTags bool

	// Specifies whether you want to apply a Legal Hold to the copied object.
	LegalHold LegalHoldStatus

	// Object Retention related fields
	Mode               RetentionMode
	RetainUntilDate    time.Time
	Expires            time.Time
	ContentType        string
	ContentEncoding    string
	ContentDisposition string
	ContentLanguage    string
	CacheControl       string

	Size int64 // Needs to be specified if progress bar is specified.
	// Progress of the entire copy operation will be sent here.
	Progress io.Reader
}

CopyDestOptions represents options specified by user for CopyObject/ComposeObject APIs

func (CopyDestOptions) Marshal

func (opts CopyDestOptions) Marshal(header http.Header)

Marshal converts all the CopyDestOptions into their equivalent HTTP header representation

type CopySrcOptions

type CopySrcOptions struct {
	Bucket, Object       string
	VersionID            string
	MatchETag            string
	NoMatchETag          string
	MatchModifiedSince   time.Time
	MatchUnmodifiedSince time.Time
	MatchRange           bool
	Start, End           int64
	Encryption           encrypt.ServerSide
}

CopySrcOptions represents a source object to be copied, using server-side copying APIs.

func (CopySrcOptions) Marshal

func (opts CopySrcOptions) Marshal(header http.Header)

Marshal converts all the CopySrcOptions into their equivalent HTTP header representation

type Core

type Core struct {
	*Client
}

Core - Inherits Client and adds new methods to expose the low level S3 APIs.

func NewCore

func NewCore(endpoint string, opts *Options) (*Core, error)

NewCore - Returns new initialized a Core client, this CoreClient should be only used under special conditions such as need to access lower primitives and being able to use them to write your own wrappers.

func (Core) AbortMultipartUpload

func (c Core) AbortMultipartUpload(ctx context.Context, bucket, object, uploadID string) error

AbortMultipartUpload - Abort an incomplete upload.

func (Core) CompleteMultipartUpload

func (c Core) CompleteMultipartUpload(ctx context.Context, bucket, object, uploadID string, parts []CompletePart, opts PutObjectOptions) (UploadInfo, error)

CompleteMultipartUpload - Concatenate uploaded parts and commit to an object.

func (Core) CopyObject

func (c Core) CopyObject(ctx context.Context, sourceBucket, sourceObject, destBucket, destObject string, metadata map[string]string, srcOpts CopySrcOptions, dstOpts PutObjectOptions) (ObjectInfo, error)

CopyObject - copies an object from source object to destination object on server side.

func (Core) CopyObjectPart

func (c Core) CopyObjectPart(ctx context.Context, srcBucket, srcObject, destBucket, destObject, uploadID string,
	partID int, startOffset, length int64, metadata map[string]string,
) (p CompletePart, err error)

CopyObjectPart - creates a part in a multipart upload by copying (a part of) an existing object.

func (Core) GetBucketPolicy

func (c Core) GetBucketPolicy(ctx context.Context, bucket string) (string, error)

GetBucketPolicy - fetches bucket access policy for a given bucket.

func (Core) GetObject

func (c Core) GetObject(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (io.ReadCloser, ObjectInfo, http.Header, error)

GetObject is a lower level API implemented to support reading partial objects and also downloading objects with special conditions matching etag, modtime etc.

func (Core) ListMultipartUploads

func (c Core) ListMultipartUploads(ctx context.Context, bucket, prefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (result ListMultipartUploadsResult, err error)

ListMultipartUploads - List incomplete uploads.

func (Core) ListObjectParts

func (c Core) ListObjectParts(ctx context.Context, bucket, object, uploadID string, partNumberMarker, maxParts int) (result ListObjectPartsResult, err error)

ListObjectParts - List uploaded parts of an incomplete upload.x

func (Core) ListObjects

func (c Core) ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (result ListBucketResult, err error)

ListObjects - List all the objects at a prefix, optionally with marker and delimiter you can further filter the results.

func (Core) ListObjectsV2

func (c Core) ListObjectsV2(bucketName, objectPrefix, startAfter, continuationToken, delimiter string, maxkeys int) (ListBucketV2Result, error)

ListObjectsV2 - Lists all the objects at a prefix, similar to ListObjects() but uses continuationToken instead of marker to support iteration over the results.

func (Core) NewMultipartUpload

func (c Core) NewMultipartUpload(ctx context.Context, bucket, object string, opts PutObjectOptions) (uploadID string, err error)

NewMultipartUpload - Initiates new multipart upload and returns the new uploadID.

func (Core) PutBucketPolicy

func (c Core) PutBucketPolicy(ctx context.Context, bucket, bucketPolicy string) error

PutBucketPolicy - applies a new bucket access policy for a given bucket.

func (Core) PutObject

func (c Core) PutObject(ctx context.Context, bucket, object string, data io.Reader, size int64, md5Base64, sha256Hex string, opts PutObjectOptions) (UploadInfo, error)

PutObject - Upload object. Uploads using single PUT call.

func (Core) PutObjectPart

func (c Core) PutObjectPart(ctx context.Context, bucket, object, uploadID string, partID int,
	data io.Reader, size int64, opts PutObjectPartOptions,
) (ObjectPart, error)

PutObjectPart - Upload an object part.

type Encryption added in v7.0.14

type Encryption struct {
	EncryptionType string
	KMSContext     string
	KMSKeyID       string `xml:"KMSKeyId"`
}

Encryption contains the type of server-side encryption used during object retrieval

type ErrorResponse

type ErrorResponse struct {
	XMLName    xml.Name `xml:"Error" json:"-"`
	Code       string
	Message    string
	BucketName string
	Key        string
	Resource   string
	RequestID  string `xml:"RequestId"`
	HostID     string `xml:"HostId"`

	// Region where the bucket is located. This header is returned
	// only in HEAD bucket and ListObjects response.
	Region string

	// Captures the server string returned in response header.
	Server string

	// Underlying HTTP status code for the returned error
	StatusCode int `xml:"-" json:"-"`
}

ErrorResponse - Is the typed error returned by all API operations. ErrorResponse struct should be comparable since it is compared inside golang http API (https://github.com/golang/go/issues/29768)

func ToErrorResponse

func ToErrorResponse(err error) ErrorResponse

ToErrorResponse - Returns parsed ErrorResponse struct from body and http headers.

For example:

import s3 "github.com/minio/minio-go/v7"
...
...
reader, stat, err := s3.GetObject(...)
if err != nil {
   resp := s3.ToErrorResponse(err)
}
...

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

Error - Returns S3 error string.

type ExcludedPrefix added in v7.0.26

type ExcludedPrefix struct {
	Prefix string
}

ExcludedPrefix - holds individual prefixes excluded from being versioned.

type GetObjectLegalHoldOptions

type GetObjectLegalHoldOptions struct {
	VersionID string
}

GetObjectLegalHoldOptions represents options specified by user for GetObjectLegalHold call

type GetObjectOptions

type GetObjectOptions struct {
	ServerSideEncryption encrypt.ServerSide
	VersionID            string
	PartNumber           int

	// Include any checksums, if object was uploaded with checksum.
	// For multipart objects this is a checksum of part checksums.
	// https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
	Checksum bool

	// To be not used by external applications
	Internal AdvancedGetOptions
	// contains filtered or unexported fields
}

GetObjectOptions are used to specify additional headers or options during GET requests.

func (*GetObjectOptions) AddReqParam added in v7.0.48

func (o *GetObjectOptions) AddReqParam(key, value string)

AddReqParam - add request query string parameter supported key: see supportedQueryValues and allowedCustomQueryPrefix. If an unsupported key is passed in, it will be ignored and nothing will be done.

func (GetObjectOptions) Header

func (o GetObjectOptions) Header() http.Header

Header returns the http.Header representation of the GET options.

func (*GetObjectOptions) Set

func (o *GetObjectOptions) Set(key, value string)

Set adds a key value pair to the options. The key-value pair will be part of the HTTP GET request headers.

func (*GetObjectOptions) SetMatchETag

func (o *GetObjectOptions) SetMatchETag(etag string) error

SetMatchETag - set match etag.

func (*GetObjectOptions) SetMatchETagExcept

func (o *GetObjectOptions) SetMatchETagExcept(etag string) error

SetMatchETagExcept - set match etag except.

func (*GetObjectOptions) SetModified

func (o *GetObjectOptions) SetModified(modTime time.Time) error

SetModified - set modified time since.

func (*GetObjectOptions) SetRange

func (o *GetObjectOptions) SetRange(start, end int64) error

SetRange - set the start and end offset of the object to be read. See https://tools.ietf.org/html/rfc7233#section-3.1 for reference.

func (*GetObjectOptions) SetReqParam added in v7.0.48

func (o *GetObjectOptions) SetReqParam(key, value string)

SetReqParam - set request query string parameter supported key: see supportedQueryValues and allowedCustomQueryPrefix. If an unsupported key is passed in, it will be ignored and nothing will be done.

func (*GetObjectOptions) SetUnmodified

func (o *GetObjectOptions) SetUnmodified(modTime time.Time) error

SetUnmodified - set unmodified time since.

type GetObjectTaggingOptions

type GetObjectTaggingOptions struct {
	VersionID string
	Internal  AdvancedObjectTaggingOptions
}

GetObjectTaggingOptions holds the object version ID to fetch the tagging key/value pairs

type GlacierJobParameters added in v7.0.14

type GlacierJobParameters struct {
	Tier TierType
}

GlacierJobParameters represents the retrieval tier parameter

type Grant added in v7.0.14

type Grant struct {
	XMLName