1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
}
|