summaryrefslogtreecommitdiff
path: root/cf-r2/download.go
diff options
context:
space:
mode:
authorJeff Carr <[email protected]>2024-12-23 01:41:48 -0600
committerJeff Carr <[email protected]>2024-12-23 01:41:48 -0600
commit1df95aec09c5ac799d84367ad3721e784eb76f30 (patch)
treeac99686b0ae52c526d4cebc25e04f1da2c0da4a6 /cf-r2/download.go
parent91060915d061674def0bbf5d3c6464c62c9eba68 (diff)
more examplesv0.0.17
Signed-off-by: Jeff Carr <[email protected]>
Diffstat (limited to 'cf-r2/download.go')
-rw-r--r--cf-r2/download.go66
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
+}