### Minio Go SDK Quick Start Example Source: https://github.com/minio/minio-go/blob/master/_autodocs/README.md This snippet demonstrates the basic workflow of the Minio Go SDK, including client initialization, bucket creation, object operations, and URL generation. Ensure you have the necessary imports and context initialized. ```go import "github.com/minio/minio-go/v7" import "github.com/minio/minio-go/v7/pkg/credentials" import "context" import "fmt" import "log" import "net/url" import "time" func main() { ctx := context.Background() // Initialize client client, err := minio.New("play.min.io", &minio.Options{ Creds: credentials.NewStaticV4("key", "secret", ""), Secure: true, }) if err != nil { log.Fatal(err) } // Create bucket err = client.MakeBucket(ctx, "mybucket", minio.MakeBucketOptions{ Region: "us-east-1", }) if err != nil { // Check to see if we already own this bucket (common error) exists, errBucketExists := client.BucketExists(ctx, "mybucket") if errBucketExists == nil && exists { log.Printf("We already own this bucket, skipping creation.") } else { log.Fatalln(err) } } // Upload object uploadInfo, err := client.FPutObject(ctx, "mybucket", "myobject.txt", "/path/to/file.txt", minio.PutObjectOptions{}) if err != nil { log.Fatalln(err) } fmt.Println("Uploaded:", uploadInfo.ETag) // Download object err = client.FGetObject(ctx, "mybucket", "myobject.txt", "/tmp/download.txt", minio.GetObjectOptions{}) if err != nil { log.Fatalln(err) } // List objects objectCh := client.ListObjects(ctx, "mybucket", minio.ListObjectsOptions{}) for object := range objectCh { fmt.Println(object.Key) } // Generate presigned URL url, err := client.PresignedGetObject(ctx, "mybucket", "myobject.txt", 24*time.Hour, url.Values{}) if err != nil { log.Fatalln(err) } fmt.Println("Shareable URL:", url.String()) } ``` -------------------------------- ### Run MinIO Go Example Source: https://github.com/minio/minio-go/blob/master/README.md These commands set up the Go environment and run the FileUploader example. Ensure you have Go installed and the necessary modules are fetched. ```sh 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 ``` -------------------------------- ### Build All Examples Source: https://github.com/minio/minio-go/blob/master/AGENTS.md Compile all example programs included in the repository. ```bash make examples ``` -------------------------------- ### Build a Specific Example Source: https://github.com/minio/minio-go/blob/master/AGENTS.md Compile a specific example program, navigating to its directory first. ```bash cd examples/s3 && go build -mod=mod putobject.go ``` -------------------------------- ### Example: Listing Object Annotations Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/listing-operations.md This example demonstrates how to call ListObjectAnnotations to retrieve annotations for objects in a bucket. It iterates over the returned channel to process each annotation. ```go annotationsCh, err := minioClient.ListObjectAnnotations( context.Background(), "mybucket", minio.ListObjectAnnotationsOptions{}, ) if err != nil { log.Fatal(err) } for annotation := range annotationsCh { fmt.Println("Annotation:", annotation) } ``` -------------------------------- ### Minio Client Configuration with Path-Style Lookup Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Example of creating a Minio client instance configured to use path-style bucket lookups. ```go opts := &minio.Options{ Creds: credentials.NewStaticV4("key", "secret", ""), Secure: true, BucketLookup: minio.BucketLookupPath, } client, _ := minio.New("minio.example.com", opts) ``` -------------------------------- ### Example: Retrieving Object Attributes Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-metadata.md Demonstrates how to call GetObjectAttributes to fetch specific attributes like ETag, ObjectSize, and StorageClass for an object. ```go attrs, err := minioClient.GetObjectAttributes( context.Background(), "mybucket", "largeobject.bin", minio.GetObjectAttributesOptions{ Attributes: []string{"ETag", "ObjectSize", "StorageClass"}, }, ) if err != nil { log.Fatal(err) } fmt.Printf("Size: %d bytes\n", attrs.ObjectSize) fmt.Printf("Storage Class: %s\n", attrs.StorageClass) ``` -------------------------------- ### Example Usage of PutObjectFanOut Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/advanced-operations.md Demonstrates how to use the PutObjectFanOut function to upload an object to multiple buckets and process the results. ```go data := []byte("Replicate this object") object := minio.FanOutObject{ Buckets: []string{"bucket-us", "bucket-eu", "bucket-ap"}, Object: "important-file.txt", Data: bytes.NewReader(data), Size: int64(len(data)), } results, err := minioClient.PutObjectFanOut(context.Background(), object) if err != nil { log.Fatal(err) } for _, result := range results { if result.Error != nil { fmt.Printf("Failed to upload to %s: %v\n", result.Bucket, result.Error) } else { fmt.Printf("Uploaded to %s (ETag: %s)\n", result.Bucket, result.ETag) } } ``` -------------------------------- ### Initialize Minio Client with Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md A complete example demonstrating the initialization of a Minio client with various options, including credentials, region, and bucket lookup strategy. ```go package main import ( "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) func main() { // Configure credentials creds := credentials.NewChain( credentials.NewEnvAWS(), credentials.NewStaticV4("fallback-key", "fallback-secret", ""), ) // Configure client opts := &minio.Options{ Creds: creds, Secure: true, Region: "us-west-2", BucketLookup: minio.BucketLookupAuto, MaxRetries: 5, } // Initialize client client, err := minio.New("s3.us-west-2.amazonaws.com", opts) if err != nil { panic(err) } // Set application info for User-Agent client.SetAppInfo("my-app", "1.0.0") // Ready to use! buckets, _ := client.ListBuckets(context.Background()) for _, bucket := range buckets { println(bucket.Name) } } ``` -------------------------------- ### Run All Checks (Lint, Test, Examples, Functional Tests) Source: https://github.com/minio/minio-go/blob/master/AGENTS.md Execute all code quality and testing checks using the make command. ```bash make checks ``` -------------------------------- ### Download MinIO Go Client SDK Source: https://github.com/minio/minio-go/blob/master/README.md Use 'go get' to download the MinIO Go Client SDK from GitHub. This command should be run from your project directory. ```sh go get github.com/minio/minio-go/v7 ``` -------------------------------- ### Example: Retrieving and Reading an Object Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-operations.md Demonstrates how to retrieve an object using GetObject, read its content into a buffer, and access its metadata using Stat. Ensure to close the object stream using defer. ```go object, err := minioClient.GetObject(context.Background(), "mybucket", "myobject.txt", minio.GetObjectOptions{}) if err != nil { log.Fatal(err) } defer object.Close() // Read object data buf := make([]byte, 1024) n, err := object.Read(buf) if err != nil { log.Fatal(err) } fmt.Printf("Read %d bytes\n", n) // Or get metadata stat, err := object.Stat() if err != nil { log.Fatal(err) } fmt.Printf("Object size: %d\n", stat.Size) ``` -------------------------------- ### Instantiate Minio Client with Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Example of creating a new Minio client instance with custom options, such as static credentials, HTTPS enabled, a specific region, and a maximum number of retries. ```go opts := &minio.Options{ Creds: credentials.NewStaticV4("accessKey", "secretKey", ""), Secure: true, Region: "us-east-1", MaxRetries: 5, } client, err := minio.New("s3.amazonaws.com", opts) ``` -------------------------------- ### Example: Copying an Object Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-operations.md Demonstrates how to copy an object from a source bucket to a destination bucket using the CopyObject function. Ensure the Minio client is initialized before use. ```go uploadInfo, err := minioClient.CopyObject( context.Background(), minio.CopyDestOptions{ Bucket: "destbucket", Object: "destobject", }, minio.CopySrcOptions{ Bucket: "sourcebucket", Object: "sourceobject", }, ) if err != nil { log.Fatal(err) } fmt.Printf("Object copied with ETag: %s\n", uploadInfo.ETag) ``` -------------------------------- ### Example: Generating Presigned Post Policy Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/presigned-operations.md Demonstrates how to create a PostPolicy, set various constraints, and then use PresignedPostPolicy to obtain the form action URL and fields for an HTML form upload. ```go policy := minio.NewPostPolicy() policy.SetBucket("mybucket") policy.SetKey("uploads/user-file.txt") policy.SetExpires(time.Now().AddDate(0, 0, 1)) // Valid for 1 day policy.SetContentLengthRange(1, 104857600) // 1 byte to 100 MB policy.SetContentType("text/plain") url, formData, err := minioClient.PresignedPostPolicy(context.Background(), policy) if err != nil { log.Fatal(err) } // Use in HTML form: fmt.Println("Form Action:", url.String()) for key, value := range formData { fmt.Printf("\n", key, value) } ``` -------------------------------- ### Configure Custom SHA256 Hasher Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Provide a custom SHA256 hasher implementation. This example uses the standard library's sha256 package. ```go opts := &minio.Options{ Creds: creds, CustomSHA256: func() md5simd.Hasher { return sha256.New() }, } client, _ := minio.New("s3.example.com", opts) ``` -------------------------------- ### Get Bucket QoS Configuration Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the Quality of Service (QoS) configuration for a bucket. This is a MinIO-specific API and requires a context and the bucket name. ```go qosConfig, err := minioClient.GetBucketQOS(context.Background(), "mybucket") if err != nil { log.Fatalln(err) } fmt.Printf("QoS configuration: %+v\n", qosConfig) ``` -------------------------------- ### Batch Object Removal Example Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-operations.md Demonstrates how to remove multiple objects from a bucket concurrently. It involves creating a channel of objects to delete, sending them to the channel, and then iterating over the results to check for errors. ```go objectsCh := make(chan minio.ObjectInfo, 100) go func() { defer close(objectsCh) objectsCh <- minio.ObjectInfo{Key: "file1.txt"} objectsCh <- minio.ObjectInfo{Key: "file2.txt"} objectsCh <- minio.ObjectInfo{Key: "file3.txt"} }() removeResults := minioClient.RemoveObjects(context.Background(), "mybucket", objectsCh, minio.RemoveObjectsOptions{}) for result := range removeResults { if result.Error != nil { fmt.Printf("Failed to delete %s: %v\n", result.ObjectName, result.Error) } else { fmt.Printf("Deleted %s\n", result.ObjectName) } } ``` -------------------------------- ### Get Object Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/types.md Options for downloading objects, including version ID, server-side encryption, and RDMA buffer settings. Used by GetObject and FGetObject. ```go type GetObjectOptions struct { VersionID string // Specific version ID ServerSideEncrypt encrypt.ServerSide // Decryption key RDMABuffer []byte // RDMA buffer (MinIO) } ``` -------------------------------- ### Verify Uploaded File with mc ls Source: https://github.com/minio/minio-go/blob/master/README.md This command uses the MinIO client (`mc`) to list objects in the specified bucket and verify the uploaded file. Ensure `mc` is installed and configured. ```sh mc ls play/testbucket ``` -------------------------------- ### Get Bucket Versioning Configuration with MinIO Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieve the current versioning configuration for a bucket. This requires initializing the MinIO client with your credentials and endpoint. ```go 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 a 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) ``` -------------------------------- ### Start Health Check Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Initiates periodic health checks on the MinIO server at a specified interval. Returns a cancellation function to stop the checks and an error if startup fails. ```go cancel, err := minioClient.HealthCheck(30 * time.Second) if err != nil { log.Fatal(err) } defer cancel() ``` -------------------------------- ### Connect to AWS S3 Regions Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Examples show connecting to the default US East (N. Virginia) region, a specific EU region, and the S3 Accelerated endpoint. Ensure `creds` are properly initialized. ```go // US East (N. Virginia) - default client, _ := minio.New("s3.amazonaws.com", &minio.Options{ Creds: creds, Secure: true, }) ``` ```go // AWS region with specific endpoint client, _ := minio.New("s3.eu-west-1.amazonaws.com", &minio.Options{ Creds: creds, Secure: true, Region: "eu-west-1", }) ``` ```go // S3 Accelerated endpoint client, _ := minio.New("s3-accelerate.amazonaws.com", &minio.Options{ Creds: creds, Secure: true, }) client.SetS3EnableDualstack(true) ``` -------------------------------- ### Copy Object in Minio (Simple) Source: https://github.com/minio/minio-go/blob/master/docs/API.md Performs a simple server-side copy of an object from a source bucket to a destination bucket. No specific conditions or partial object copying are applied in this basic example. ```go // 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(), dstOpts, srcOpts) if err != nil { fmt.Println(err) return } fmt.Println("Successfully copied object:", uploadInfo) ``` -------------------------------- ### Get Object ACL Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-metadata.md Retrieves the Access Control List (ACL) for a specific object within a bucket. Ensure you have the necessary permissions to access the object's ACL. The example demonstrates how to fetch and print the object owner's ID. ```Go acl, err := minioClient.GetObjectACL( context.Background(), "mybucket", "myobject.txt", minio.GetObjectACLOptions{}, ) if err != nil { log.Fatal(err) } fmt.Println("Object Owner:", acl.Owner.ID) ``` -------------------------------- ### Get Bucket Replication Resync Status Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieve the status of a replication resync operation. This is a MinIO specific extension. Pass an empty string for the ARN to get status for all targets. ```go // Get resync status for all targets resyncInfo, err := minioClient.GetBucketReplicationResyncStatus(context.Background(), "my-bucketname", "") if err != nil { log.Fatalln(err) } fmt.Printf("Resync status: %+v\n", resyncInfo) ``` -------------------------------- ### GetBucketReplicationMetrics Source: https://github.com/minio/minio-go/blob/master/docs/API.md Get replication metrics for a bucket. This is a MinIO specific extension. ```APIDOC ## GetBucketReplicationMetrics ### Description Get replication metrics for a bucket. This is a MinIO specific extension. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - `ctx` (context.Context) - Required - Custom context for timeout/cancellation of the call - `bucketName` (string) - Required - Name of the bucket ### Request Example ```go metrics, err := minioClient.GetBucketReplicationMetrics(context.Background(), "mybucket") if err != nil { log.Fatalln(err) } fmt.Printf("Replication metrics: %+v\n", metrics) ``` ### Response #### Success Response (200) - `metrics` (replication.Metrics) - Replication metrics - `err` (error) - Standard Error #### Response Example - None (The return values are directly provided by the function signature) ``` -------------------------------- ### Client Initialization Source: https://github.com/minio/minio-go/blob/master/_autodocs/INDEX.md Demonstrates how to initialize a MinIO client with specified endpoint, credentials, and security options. ```APIDOC ## Client Initialization ### Description Initialize a MinIO client with your S3-compatible storage endpoint, access key, secret key, and security settings. ### Method `minio.New(endpoint string, opts *Options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import "github.com/minio/minio-go/v7" import "github.com/minio/minio-go/v7/pkg/credentials" client, err := minio.New("play.min.io", &minio.Options{ Creds: credentials.NewStaticV4("accessKey", "secretKey", ""), Secure: true, }) ``` ### Response #### Success Response (200) - **client** (*minio.Client) - Initialized MinIO client object. - **err** (*error) - Error if initialization fails. #### Response Example None ``` -------------------------------- ### Get Credentials Context Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Obtains a pointer to the CredContext, which can be used for advanced credential management operations. ```go c.CredContext() ``` -------------------------------- ### Get Bucket Inventory Configuration Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieve the inventory configuration for a specific bucket. This is a MinIO-specific API. ```go config, err := minioClient.GetBucketInventoryConfiguration(context.Background(), "mybucket", "inventory1") if err != nil { log.Fatalln(err) } fmt.Printf("Inventory: %+v\n", config) ``` -------------------------------- ### Initialize Minio Client Source: https://github.com/minio/minio-go/blob/master/_autodocs/INDEX.md Initializes a Minio client with static credentials and endpoint configuration. Ensure you have the necessary credentials and endpoint details. ```go creds := credentials.NewStaticV4(accessKey, secretKey, "") client, err := minio.New(endpoint, &minio.Options{ Creds: creds, Secure: true, }) ``` -------------------------------- ### Get Object Retention Policy Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the retention mode and retain-until date for a specific object version. ```go mode, retainUntilDate, err := minioClient.GetObjectRetention(context.Background(), "mybucket", "myobject", "") if err != nil { fmt.Println(err) return } fmt.Printf("Retention mode: %v, Retain until: %v\n", mode, retainUntilDate) ``` -------------------------------- ### Get Bucket Tags Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves all tags associated with a bucket. This is useful for auditing or verifying bucket configurations. ```go tags, err := minioClient.GetBucketTagging(context.Background(), "my-bucketname") if err != nil { log.Fatalln(err) } fmt.Printf("Fetched Object Tags: %v\n", tags) ``` -------------------------------- ### Create a Bucket Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-operations.md Use MakeBucket to create a new bucket. Optionally enable object locking or force creation if the bucket already exists (MinIO specific). ```go err := minioClient.MakeBucket(context.Background(), "mybucket", minio.MakeBucketOptions{ Region: "us-east-1", ObjectLocking: false, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Set Bucket Encryption Configuration Source: https://github.com/minio/minio-go/blob/master/docs/API.md Configures default encryption for a bucket. This example demonstrates setting SSE-S3 encryption. ```go 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) } ``` -------------------------------- ### Initialize MinIO Client Source: https://github.com/minio/minio-go/blob/master/_autodocs/INDEX.md Initializes a new MinIO client. Ensure you have the necessary credentials and endpoint configured. The 'Secure' option should be set based on your server's TLS configuration. ```go import "github.com/minio/minio-go/v7" import "github.com/minio/minio-go/v7/pkg/credentials" client, err := minio.New("play.min.io", &minio.Options{ Creds: credentials.NewStaticV4("accessKey", "secretKey", ""), Secure: true, }) ``` -------------------------------- ### Get Client Credentials Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the current credentials used by the client. Useful for debugging or passing credentials to other components. ```go creds, err := minioClient.GetCreds() if err != nil { log.Fatalln(err) } fmt.Printf("Access Key: %s\n", creds.AccessKeyID) ``` -------------------------------- ### Get Bucket Location Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the region or location constraint of a specified bucket. Ensure the bucket exists before calling. ```go location, err := minioClient.GetBucketLocation(context.Background(), "mybucket") if err != nil { log.Fatalln(err) } fmt.Printf("Bucket location: %s\n", location) ``` -------------------------------- ### Get Bucket Replication Configuration Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the current replication configuration for a specified bucket. Ensure the bucket name is correct. ```go replication, err := minioClient.GetBucketReplication(context.Background(), "my-bucketname") if err != nil { log.Fatalln(err) } ``` -------------------------------- ### Configure HTTP Trace Client Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Set up a ClientTrace to capture DNS, connection, and other HTTP-related events. This trace is then passed to the Minio client options. ```go import "net/http/httptrace" trace := &httptrace.ClientTrace{ DNSStart: func(info httptrace.DNSStartInfo) { fmt.Printf("DNS lookup for %s\n", info.Host) }, DNSDone: func(info httptrace.DNSDoneInfo) { if info.Err != nil { fmt.Printf("DNS error: %v\n", info.Err) } }, ConnectStart: func(network, addr string) { fmt.Printf("Connecting to %s\n", addr) }, } client, _ := minio.New("s3.example.com", &minio.Options{ Creds: creds, Secure: true, Trace: trace, }) ``` -------------------------------- ### Get Bucket Notification Configuration Source: https://github.com/minio/minio-go/blob/master/docs/API.md Fetches the notification configuration for a given bucket. This is useful for inspecting current notification settings. ```go 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") } } ``` -------------------------------- ### Get Bucket Policy Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the access permissions policy for a specified bucket. Ensure you have the necessary permissions to perform this operation. ```go policy, err := minioClient.GetBucketPolicy(context.Background(), "my-bucketname") if err != nil { log.Fatalln(err) } ``` -------------------------------- ### Upload a File to MinIO Source: https://github.com/minio/minio-go/blob/master/README.md This Go program connects to a MinIO server, creates a bucket, uploads a file, and logs the success. Ensure the MinIO server is running and accessible with the provided credentials. ```go // 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) } ``` -------------------------------- ### Get Bucket CORS Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-configuration.md Retrieves the current CORS configuration for a bucket. This is useful for inspecting or modifying existing settings. ```go corsConfig, err := minioClient.GetBucketCors(context.Background(), "mybucket") if err != nil { log.Fatal(err) } fmt.Println("CORS Rules:", corsConfig) ``` -------------------------------- ### Object Methods Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-operations.md Provides methods for interacting with a retrieved object, including reading data, getting metadata, and closing the stream. ```go type Object struct { // Read reads up to len(b) bytes from the object Read(p []byte) (n int, err error) // Stat returns object metadata without reading content Stat() (ObjectInfo, error) // Close closes the object stream Close() error } ``` -------------------------------- ### Initialize MinIO Client (AWS S3) Source: https://github.com/minio/minio-go/blob/master/docs/API.md Demonstrates how to initialize a MinIO client object for connecting to AWS S3. ```APIDOC ## Initialize MinIO Client (AWS S3) ### Description Initializes a MinIO client object for interacting with AWS S3. ### Usage ```go import ( "fmt" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) func main() { 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 } } ``` ``` -------------------------------- ### PostPolicy Methods for Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/presigned-operations.md Provides methods to configure various aspects of a PostPolicy, such as bucket, key, expiration, content type, and size constraints. ```go // SetBucket sets the bucket name func (p *PostPolicy) SetBucket(bucketName string) *PostPolicy // SetKey sets the object key/name func (p *PostPolicy) SetKey(objectName string) *PostPolicy // SetExpires sets the policy expiration time func (p *PostPolicy) SetExpires(expiration time.Time) *PostPolicy // SetContentType sets the allowed content type func (p *PostPolicy) SetContentType(contentType string) *PostPolicy // SetContentLengthRange sets min and max object size func (p *PostPolicy) SetContentLengthRange(min, max int64) *PostPolicy // SetSuccessActionStatus sets HTTP status for successful upload func (p *PostPolicy) SetSuccessActionStatus(code int) *PostPolicy // SetUserMetadata sets custom metadata headers func (p *PostPolicy) SetUserMetadata(key, value string) *PostPolicy ``` -------------------------------- ### Create New QOSConfig Instance Source: https://github.com/minio/minio-go/blob/master/_autodocs/types.md Provides a constructor function to create a new instance of QOSConfig. ```go func NewQOSConfig() *QOSConfig ``` -------------------------------- ### Get Bucket Replication Metrics Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Fetches replication metrics for a bucket. This is a MinIO-specific feature and requires the bucket to have replication configured. ```go metrics, err := minioClient.GetBucketReplicationMetrics(context.Background(), "mybucket") if err != nil { log.Fatalln(err) } fmt.Printf("Replication metrics: %+v\n", metrics) ``` -------------------------------- ### Connect to MinIO Server Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Demonstrates connecting to a MinIO server using HTTP for development or HTTPS for production. Static credentials are used for authentication. ```go // HTTP (development) client, _ := minio.New("localhost:9000", &minio.Options{ Creds: credentials.NewStaticV4("minioadmin", "minioadmin", ""), Secure: false, }) ``` ```go // HTTPS (production) client, _ := minio.New("minio.example.com:9000", &minio.Options{ Creds: credentials.NewStaticV4("minioadmin", "minioadmin", ""), Secure: true, }) ``` -------------------------------- ### Create a Test File Source: https://github.com/minio/minio-go/blob/master/README.md These commands create a sample file for testing MinIO uploads. Choose the command appropriate for your operating system. ```sh dd if=/dev/urandom of=/tmp/testdata bs=2048 count=10 ``` ```powershell fsutil file createnew "C:\Users\\Desktop\sample.txt" 20480 ``` -------------------------------- ### Get Endpoint URL Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the URL of the S3-compatible endpoint the client is connected to. Returns a copy to prevent modification of internal state. ```go endpointURL := minioClient.EndpointURL() fmt.Printf("Connected to: %s\n", endpointURL.String()) ``` -------------------------------- ### Initialize MinIO Client for MinIO Source: https://github.com/minio/minio-go/blob/master/docs/API.md Initializes a MinIO client object for connecting to a MinIO service. Ensure you have the 'minio-go/v7' package imported. ```go 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 } ``` -------------------------------- ### Get Object Annotation in Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves the payload of a named annotation for an object version. The caller is responsible for closing the returned io.ReadCloser. ```go body, err := minioClient.GetObjectAnnotation(context.Background(), bucketName, objectName, "model.labels.json", minio.GetObjectAnnotationOptions{}) if err != nil { fmt.Println(err) return } defer body.Close() if _, err := io.Copy(os.Stdout, body); err != nil { fmt.Println(err) return } ``` -------------------------------- ### Get Bucket Encryption Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-configuration.md Retrieves the current server-side encryption configuration for a bucket. This is useful for auditing or verifying encryption settings. ```go config, err := minioClient.GetBucketEncryption(context.Background(), "mybucket") if err != nil { log.Fatal(err) } fmt.Println("Encryption:", config) ``` -------------------------------- ### New Client Initialization Source: https://github.com/minio/minio-go/blob/master/docs/API.md Initializes a new Minio client object with the specified endpoint and options. This is the entry point for interacting with Minio storage. ```APIDOC ## New(endpoint string, opts *Options) (*Client, error) ### Description Initializes a new client object. ### Parameters #### Path Parameters - **endpoint** (string) - Required - S3 compatible object storage endpoint - **opts** (*minio.Options) - Required - Options for constructing a new client ### minio.Options #### Fields - **Creds** (*credentials.Credentials) - Optional - S3 compatible object storage access credentials - **Secure** (bool) - Optional - If 'true' API requests will be secure (HTTPS), and insecure (HTTP) otherwise - **Transport** (http.RoundTripper) - Optional - Custom transport for executing HTTP transactions - **Region** (string) - Optional - S3 compatible object storage region - **BucketLookup** (BucketLookupType) - Optional - Bucket lookup type can be one of the following values: _minio.BucketLookupDNS_, _minio.BucketLookupPath_, _minio.BucketLookupAuto_ ``` -------------------------------- ### Code Formatting Source: https://github.com/minio/minio-go/blob/master/CONTRIBUTING.md Format your code using `go fmt` to ensure consistency with project standards. ```bash go fmt ``` -------------------------------- ### Get Bucket Versioning Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-configuration.md Retrieves the current versioning configuration for a specified bucket. This allows you to check if versioning is enabled or suspended. ```go config, err := minioClient.GetBucketVersioning(context.Background(), "mybucket") if err != nil { log.Fatal(err) } if config.Enabled() { fmt.Println("Versioning is enabled") } ``` -------------------------------- ### Get Object Retention Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/object-metadata.md Defines the structure for retrieving object retention settings, primarily used for specifying a version ID. ```go type GetObjectRetentionOptions struct { VersionID string // Specific version ID } ``` -------------------------------- ### Initiate Bucket Replication Reset Source: https://github.com/minio/minio-go/blob/master/docs/API.md Use this to initiate replication of previously replicated objects to a specific target. Requires ExistingObjectReplication to be enabled. This is a MinIO specific extension. ```go resyncInfo, err := minioClient.ResetBucketReplicationOnTarget(context.Background(), "my-bucketname", 0, "arn:aws:s3:::target-bucket") if err != nil { log.Fatalln(err) } fmt.Printf("Resync info: %+v\n", resyncInfo) ``` -------------------------------- ### Make Bucket Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/types.md Options for creating a new bucket, including region, object locking, and force creation. Used by MakeBucket. ```go type MakeBucketOptions struct { Region string // AWS region (default: "us-east-1") ObjectLocking bool // Enable object lock for WORM ForceCreate bool // MinIO extension: force creation } ``` -------------------------------- ### Enable Versioning - Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Enable versioning support for a bucket. This operation is irreversible once enabled. ```go err := minioClient.EnableVersioning(context.Background(), "my-bucketname") if err != nil { log.Fatalln(err) } fmt.Println("versioning enabled for bucket 'my-bucketname'") ``` -------------------------------- ### Get Bucket QoS Metrics Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves Quality of Service (QoS) metrics for a bucket across all nodes or a specific node. This is a MinIO-specific feature. ```go // Get QoS metrics for all nodes metrics, err := minioClient.GetBucketQOSMetrics(context.Background(), "mybucket", "") if err != nil { log.Fatalln(err) } for _, nodeStats := range metrics { fmt.Printf("Node: %s, Stats: %+v\n", nodeStats.NodeName, nodeStats.Stats) } ``` -------------------------------- ### Enable Application Information Header Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Set application name and version to be included in the User-Agent header. This helps in identifying client applications interacting with Minio. ```go client.SetAppInfo("my-app", "1.0.0") // User-Agent header will now include: my-app/1.0.0 ``` -------------------------------- ### Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/README.md Guidance on configuring the MinIO client, including options, credential providers, endpoint configurations, and transport customization. ```APIDOC ## Configuration ### Description Details the configuration options for the MinIO client, covering the `Options` struct fields, various credential providers (static, env, IAM, STS, chain), endpoint configurations (AWS S3, MinIO, custom), URL styles, HTTP transport customization, retry settings, tracing, debugging, and hash function customization. ### Key Areas - `Options` struct reference (13 options). - Credential providers. - Endpoint configuration. - URL style configuration. - HTTP transport customization. - Retry configuration. - Tracing and debugging. - Hash function customization. - Complete examples provided. ### Related Files - `configuration.md` ``` -------------------------------- ### Get Bucket Replication Metrics V2 Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieves enhanced replication metrics for a bucket using the V2 API. This is a MinIO specific extension. ```go replMetrics, err := minioClient.GetBucketReplicationMetricsV2(context.Background(), "my-bucketname") if err != nil { log.Fatalln(err) } fmt.Printf("Replication metrics: %+v\n", replMetrics) ``` -------------------------------- ### Define QOSConfig and QOSRule Structures Source: https://github.com/minio/minio-go/blob/master/_autodocs/types.md Defines the structures for Quality of Service (QOS) configuration for Minio buckets, including rules. ```go type QOSConfig struct { Rules []QOSRule } type QOSRule struct { // Rule configuration fields } ``` -------------------------------- ### Get Object Lock Configuration - Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md Retrieve the object lock configuration for a specified bucket. Handles cases where object lock is not enabled. ```go 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'") } ``` -------------------------------- ### Get Client Endpoint URL Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Retrieves a copy of the client's endpoint URL. This prevents modification of the client's internal state. ```go url := minioClient.EndpointURL() fmt.Println(url.String()) // "https://play.min.io" ``` -------------------------------- ### New MinIO Client Constructor Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md Creates a new MinIO client instance. Use this to establish a connection to an S3-compatible endpoint with specified options. ```go func New(endpoint string, opts *Options) (*Client, error) ``` ```go import ( "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) minioClient, err := minio.New("play.min.io", &minio.Options{ Creds: credentials.NewStaticV4("accessKeyID", "secretAccessKey", ""), Secure: true, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### List Bucket Inventory Configurations Go Source: https://github.com/minio/minio-go/blob/master/docs/API.md List inventory configurations for a bucket with pagination support. This is a MinIO-specific API. ```go result, err := minioClient.ListBucketInventoryConfigurations(context.Background(), "mybucket", "") if err != nil { log.Fatalln(err) } for _, item := range result.Items { fmt.Printf("Inventory ID: %s\n", item.ID) } if result.NextContinuationToken != "" { // Fetch next page nextResult, _ := minioClient.ListBucketInventoryConfigurations(context.Background(), "mybucket", result.NextContinuationToken) } ``` -------------------------------- ### Get Bucket Lifecycle Configuration Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-configuration.md Retrieves the current lifecycle configuration for a specified bucket. Use this to inspect existing object management policies. ```go config, err := minioClient.GetBucketLifecycle(context.Background(), "mybucket") if err != nil { log.Fatal(err) } for _, rule := range config.Rules { fmt.Println("Rule:", rule.ID) } ``` -------------------------------- ### Get Bucket Policy - Go Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-configuration.md Retrieves the current bucket policy for a specified bucket as a JSON string. Returns an error if the policy cannot be retrieved. ```go policy, err := minioClient.GetBucketPolicy(context.Background(), "mybucket") if err != nil { log.Fatal(err) } fmt.Println("Bucket Policy:", policy) ``` -------------------------------- ### Minio Client Initialization Options Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/client.md The Options struct is used to configure the Minio client during initialization. It allows customization of credentials, security settings, HTTP transport, region, bucket lookup strategies, and retry behavior. ```APIDOC ## New Minio Client with Options ### Description This section details the `Options` struct used for configuring the Minio client. It allows for fine-grained control over various aspects of the client's behavior, such as authentication, network transport, and error handling. ### Parameters #### Request Body (Options Struct) - **Creds** (*credentials.Credentials) - Yes - Credentials provider for authentication - **Secure** (bool) - No - Use HTTPS for connections (default: false) - **Transport** (http.RoundTripper) - No - Custom HTTP transport layer (default: DefaultTransport) - **Trace** (*httptrace.ClientTrace) - No - HTTP trace for debugging (default: nil) - **Region** (string) - No - AWS region (auto-detected if empty) (default: "") - **BucketLookup** (BucketLookupType) - No - URL lookup strategy (default: BucketLookupAuto) - **CustomRegionViaURL** (func) - No - Custom region lookup function (default: nil) - **BucketLookupViaURL** (func) - No - Custom bucket lookup strategy (default: nil) - **TrailingHeaders** (bool) - No - Support for trailing headers in v4 signatures (default: false) - **CustomMD5** (func) - No - Custom MD5 hasher factory (default: nil) - **CustomSHA256** (func) - No - Custom SHA256 hasher factory (default: nil) - **MaxRetries** (int) - No - Maximum request retries on transient failures (default: 10) - **EnableRDMA** (bool) - No - Enable RDMA for PutObject/GetObject (requires build tag) (default: false) ### Request Example ```go opts := &minio.Options{ Creds: credentials.NewStaticV4("accessKey", "secretKey", ""), Secure: true, Region: "us-east-1", MaxRetries: 5, } client, err := minio.New("s3.amazonaws.com", opts) ``` ### Response #### Success Response (200) - **client** (*minio.Client) - The initialized Minio client instance. - **err** (error) - An error if the client initialization failed. #### Response Example ```go // Successful initialization // client is a *minio.Client // err is nil // Failed initialization // client is nil // err is an error object ``` ``` -------------------------------- ### Get Bucket Location in MinIO Source: https://github.com/minio/minio-go/blob/master/_autodocs/api-reference/bucket-operations.md Retrieves the AWS region where a specific bucket is located. Requires the bucket name and a context for cancellation and timeouts. ```go func (c *Client) GetBucketLocation(ctx context.Context, bucketName string) (string, error) ``` ```go location, err := minioClient.GetBucketLocation(context.Background(), "mybucket") if err != nil { log.Fatal(err) } fmt.Println("Bucket location:", location) ``` -------------------------------- ### Git Workflow for Contributions Source: https://github.com/minio/minio-go/blob/master/CONTRIBUTING.md Follow these steps to fork the project, create a feature branch, commit changes, and prepare a pull request. ```bash git checkout -b my-new-feature ``` ```bash git commit -am 'Add some feature' ``` ```bash git push origin my-new-feature ``` -------------------------------- ### Configure Connection Pooling Source: https://github.com/minio/minio-go/blob/master/_autodocs/configuration.md Set MaxIdleConns, MaxIdleConnsPerHost, and MaxConnsPerHost on http.Transport for efficient connection management. ```go transport := &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 100, MaxConnsPerHost: 100, } client, _ := minio.New("s3.example.com", &minio.Options{ Transport: transport, }) ```