diff options
| author | Jeff Carr <[email protected]> | 2025-01-06 03:05:47 -0600 |
|---|---|---|
| committer | Jeff Carr <[email protected]> | 2025-01-06 03:05:47 -0600 |
| commit | 35bec795e7195e967d95399329fe7b6d0b7cc069 (patch) | |
| tree | 3f1085a03ff5398a4299886342a6802e6b6f4822 /cf-r2/download.go | |
| parent | 8f9b66f6c8565f08e18098e330dfe73c22592b9f (diff) | |
| parent | 98b0d445bc513c5439421d1ec0d32874fc1350f9 (diff) | |
Merge branch 'jcarr' of gitea.wit.com:jcarr/wit-utils into jcarr
Diffstat (limited to 'cf-r2/download.go')
| -rw-r--r-- | cf-r2/download.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/cf-r2/download.go b/cf-r2/download.go new file mode 100644 index 0000000..b2f4184 --- /dev/null +++ b/cf-r2/download.go @@ -0,0 +1,66 @@ +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 +} |
