Categorygithub.com/minio/minio-go/v7
modulepackage
7.0.87
Repository: https://github.com/minio/minio-go.git
Documentation: pkg.go.dev

# 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:

ParameterDescription
endpointURL 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.

# Packages

# Functions

IsNetworkOrHostDown - if there was a network error or if the host is down.
New - instantiate minio client with options.
NewChecksum sets the checksum to the value of b, which is the raw hash output.
NewChecksumString sets the checksum to the value of s, which is the base 64 encoded raw hash output.
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.
NewPostPolicy - Instantiate new post policy.
NewSelectResults creates a Select Result parser that parses the response and returns a Reader that will return parsed and assembled select output.
OptimalPartInfo - calculate the optimal part info for a given object size.
ToErrorResponse - Returns parsed ErrorResponse struct from body and http headers.
ToObjectInfo converts http header values into ObjectInfo type, extracts metadata and fills in all the necessary fields in ObjectInfo.

# Constants

Different types of url lookup supported by the server.Initialized to BucketLookupAuto.
Different types of url lookup supported by the server.Initialized to BucketLookupAuto.
Different types of url lookup supported by the server.Initialized to BucketLookupAuto.
ChecksumCRC32 indicates a CRC32 checksum with IEEE table.
ChecksumCRC32C indicates a CRC32 checksum with Castagnoli table.
ChecksumCRC64NVME indicates CRC64 with 0xad93d23594c93659 polynomial.
ChecksumFullObject is a modifier that can be used on CRC32 and CRC32C to indicate full object checksums.
ChecksumFullObjectCRC32 indicates full object CRC32.
ChecksumFullObjectCRC32C indicates full object CRC32C.
ChecksumNone indicates no checksum.
ChecksumSHA1 indicates a SHA-1 checksum.
ChecksumSHA256 indicates a SHA256 checksum.
Compliance - compliance mode.
Constants for file header info.
Constants for file header info.
Constants for file header info.
Constants for csv quote styles.
Constants for csv quote styles.
Days - denotes no.
Various supported states.
ETag is a common response header.
GetObjectAttributesMaxParts defined the default maximum number of parts returned by GetObjectAttributes.
GetObjectAttributesTags are tags used to defined return values for the GetObjectAttributes API.
Governance - governance mode.
Constants for JSONTypes.
Constants for JSONTypes.
LegalHoldDisabled indicates legal hold is disabled.
LegalHoldEnabled indicates legal hold is enabled.
MaxJitter will randomize over the full exponential backoff time.
NoJitter disables the use of jitter for randomizing the exponential backoff time.
Constants for expression type.
ReplicationStatusComplete indicates replication completed ok.
ReplicationStatusFailed indicates replication failed.
ReplicationStatusPending indicates replication is pending.
ReplicationStatusReplica indicates object is a replica of a source.
ReplicationStatusReplicaEdge indicates object is a replica of a edge source.
RestoreSelect represents the restore SELECT operation.
Constants for compression types under select API.
Constants for compression types under select API.
LZ4 Stream.
Constants for compression types under select API.
S2 Stream.
Snappy stream.
Zstandard compression.
Constants for input data types.
Constants for input data types.
Constants for input data types.
Disabled State = "Disabled" only used by MFA Delete not supported yet.
TierBulk is the bulk retrieval tier.
TierExpedited is the expedited retrieval tier.
TierStandard is the standard retrieval tier.
Years - denotes no.

# Variables

DefaultRetryCap - Each retry attempt never waits no longer than this maximum time duration.
DefaultRetryUnit - default unit multiplicative per retry.
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.
MaxRetry is the maximum number of retries before stopping.

# Structs

AccessControlList contains the set of grantees and the permissions assigned to each grantee.
AdvancedGetOptions for internal use by MinIO server - not intended for client use.
AdvancedObjectTaggingOptions for internal use by MinIO server - not intended for client use.
AdvancedPutOptions for internal use - to be utilized by replication, ILM transition implementation on MinIO server.
AdvancedRemoveOptions intended for internal use by replication.
BucketInfo container for bucket metadata.
BucketVersioningConfiguration is the versioning configuration structure.
Checksum is a type and encoded value.
Client implements Amazon S3 compatible methods.
CommonPrefix container for prefix response.
CompletePart sub container lists individual part numbers and their md5sum, part of completeMultipartUpload.
CopyDestOptions represents options specified by user for CopyObject/ComposeObject APIs.
CopySrcOptions represents a source object to be copied, using server-side copying APIs.
Core - Inherits Client and adds new methods to expose the low level S3 APIs.
CSVInputOptions csv input specific options.
CSVOutputOptions csv output specific options.
Encryption contains the type of server-side encryption used during object retrieval.
ErrorResponse - Is the typed error returned by all API operations.
ExcludedPrefix - holds individual prefixes excluded from being versioned.
GetObjectLegalHoldOptions represents options specified by user for GetObjectLegalHold call.
GetObjectOptions are used to specify additional headers or options during GET requests.
GetObjectTaggingOptions holds the object version ID to fetch the tagging key/value pairs.
GlacierJobParameters represents the retrieval tier parameter.
Grant holds grant information.
Grantee represents the person being granted permissions.
JSONInputOptions json input specific options.
JSONOutputOptions - json output specific options.
ListBucketResult container for listObjects response.
ListBucketV2Result container for listObjects response version 2.
ListMultipartUploadsResult container for ListMultipartUploads response.
ListObjectPartsResult container for ListObjectParts response.
ListObjectsOptions holds all options of a list object request.
ListVersionsResult is an element in the list object versions response and has a special Unmarshaler because we need to preserver the order of <Version> and <DeleteMarker> in ListVersionsResult.Versions slice.
MakeBucketOptions holds all options to tweak bucket creation.
MetadataEntry represents a metadata information of the restored object.
Object represents an open object.
ObjectAttributePart is used by ObjectAttributesResponse to describe an object part.
ObjectAttributes is the response object returned by the GetObjectAttributes API - VersionID The object version - LastModified The last time the object was modified - ObjectAttributesResponse Contains more information about the object.
ObjectAttributesOptions are options used for the GetObjectAttributes API - MaxParts How many parts the caller wants to be returned (default: 1000) - VersionID The object version you want to attributes for - PartNumberMarker the listing will start AFTER the part matching PartNumberMarker - ServerSideEncryption The server-side encryption algorithm used when storing this object in Minio.
ObjectAttributesResponse contains details returned by the GetObjectAttributes API Noteworthy fields: - ObjectParts.PartsCount Contains the total part count for the object (not the current response) - ObjectParts.PartNumberMarker Pagination of parts will begin at (but not include) PartNumberMarker - ObjectParts.NextPartNumberMarket The next PartNumberMarker to be used in order to continue pagination - ObjectParts.IsTruncated Indicates if the last part is included in the request (does not check if parts are missing from the start of the list, ONLY the end) - ObjectParts.MaxParts Reflects the MaxParts used by the caller or the default MaxParts value of the API.
ObjectInfo container for object metadata.
ObjectMultipartInfo container for multipart object metadata.
ObjectPart container for particular part of an object.
Options for New method.
OutputLocation holds properties of the copy of the archived object.
Owner name.
ParquetInputOptions parquet input specific options.
PostPolicy - Provides strict static type conversion and validation for Amazon S3's POST policy JSON string.
ProgressMessage is a struct for progress xml message.
PromptObjectOptions provides options to PromptObject call.
PutObjectFanOutEntry is per object entry fan-out metadata.
PutObjectFanOutRequest this is the request structure sent to the server to fan-out the stream to multiple objects.
PutObjectFanOutResponse this is the response structure sent by the server upon success or failure for each object fan-out keys.
PutObjectLegalHoldOptions represents options specified by user for PutObjectLegalHold call.
PutObjectOptions represents options specified by user for PutObject call.
PutObjectPartOptions contains options for PutObjectPart API.
PutObjectRetentionOptions represents options specified by user for PutObject call.
PutObjectTaggingOptions holds an object version id to update tag(s) of a specific object version.
RemoveBucketOptions special headers to purge buckets, only useful when endpoint is MinIO.
RemoveObjectError - container of Multi Delete S3 API error.
RemoveObjectOptions represents options specified by user for RemoveObject call.
RemoveObjectResult - container of Multi Delete S3 API result.
RemoveObjectsOptions represents options specified by user for RemoveObjects call.
RemoveObjectTaggingOptions holds the version id of the object to remove.
RestoreInfo contains information of the restore operation of an archived object.
RestoreRequest holds properties of the restore object request.
Retention - bucket level retention configuration.
S3 holds properties of the copy of the archived object.
SelectObjectInputSerialization - input serialization parameters.
SelectObjectOptions - represents the input select body.
SelectObjectOutputSerialization - output serialization parameters.
SelectParameters holds the select request parameters.
SelectResults is used for the streaming responses from the server.
SnowballObject contains information about a single object to be added to the snowball.
SnowballOptions contains options for PutObjectsSnowball calls.
StatsMessage is a struct for stat xml message.
UploadInfo contains information about the newly uploaded or copied object.
Version is an element in the list object versions response.

# Type aliases

BucketLookupType is type of url lookup supported by server.
Deprecated: BucketOptions will be renamed to RemoveBucketOptions in future versions.
ChecksumType contains information about the checksum type.
CSVFileHeaderInfo - is the parameter for whether to utilize headers.
CSVQuoteFields - is the parameter for how CSV fields are quoted.
JSONType determines json input serialization type.
LegalHoldStatus - object legal hold status.
QueryExpressionType - is of what syntax the expression is, this should only be SQL.
ReplicationStatus represents replication status of object.
RestoreType represents the restore request type.
RetentionMode - object retention mode.
SelectCompressionType - is the parameter for what type of compression is present.
SelectObjectType - is the parameter which defines what type of object the operation is being performed on.
StatObjectOptions are used to specify additional headers or options during GET info/stat requests.
StringMap represents map with custom UnmarshalXML.
TierType represents a retrieval tier.
URLMap represents map with custom UnmarshalXML.
ValidityUnit - retention validity unit.