wit-utils/cf-r2/download.go

67 lines
1.9 KiB
Go

package main
import (
"context"
"fmt"
"log"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
const (
r2Endpoint = "<account-id>.r2.cloudflarestorage.com" // Replace with your R2 endpoint
r2AccessKey = "<your-access-key>" // Replace with your Access Key
r2SecretKey = "<your-secret-key>" // Replace with your Secret Key
r2BucketName = "example-bucket" // Replace with your bucket name
)
func main() {
// Initialize MinIO client for Cloudflare R2
client, err := minio.New(r2Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(r2AccessKey, r2SecretKey, ""),
Secure: true, // Use HTTPS
})
if err != nil {
log.Fatalf("Failed to initialize client: %v", err)
}
// Upload a file
err = uploadFile(client, "example.txt", "example.txt")
if err != nil {
log.Fatalf("Upload failed: %v", err)
}
// Download the file
err = downloadFile(client, "example.txt", "downloaded-example.txt")
if err != nil {
log.Fatalf("Download failed: %v", err)
}
}
// UploadFile uploads a file to the R2 bucket
func uploadFile(client *minio.Client, objectName, filePath string) error {
ctx := context.Background()
_, err := client.FPutObject(ctx, r2BucketName, objectName, filePath, minio.PutObjectOptions{
ContentType: "application/octet-stream", // Adjust MIME type if needed
})
if err != nil {
return fmt.Errorf("failed to upload file: %w", err)
}
fmt.Printf("Successfully uploaded %s as %s\n", filePath, objectName)
return nil
}
// DownloadFile downloads a file from the R2 bucket
func downloadFile(client *minio.Client, objectName, destPath string) error {
ctx := context.Background()
err := client.FGetObject(ctx, r2BucketName, objectName, destPath, minio.GetObjectOptions{})
if err != nil {
return fmt.Errorf("failed to download file: %w", err)
}
fmt.Printf("Successfully downloaded %s to %s\n", objectName, destPath)
return nil
}