summaryrefslogtreecommitdiff
path: root/cf-r2-awsapi/main.go
blob: bea845d454a82a20343c66497a73de8f892b53f6 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
)

const (
	r2AccountID   = "<your-account-id>"      // Replace with your Cloudflare R2 Account ID
	r2AccessKey   = "<your-access-key-id>"   // Replace with your Access Key ID
	r2SecretKey   = "<your-secret-access-key>" // Replace with your Secret Access Key
	r2BucketName  = "example-bucket"         // Replace with your bucket name
	r2Endpoint    = "https://<account-id>.r2.cloudflarestorage.com" // Replace with your endpoint
)

func main() {
	// Initialize the AWS Config for R2
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(aws.NewCredentialsCache(
			aws.NewStaticCredentialsProvider(r2AccessKey, r2SecretKey, ""),
		)),
		config.WithEndpointResolver(aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
			return aws.Endpoint{URL: r2Endpoint}, nil
		})),
	)
	if err != nil {
		log.Fatalf("Unable to load AWS config: %v", err)
	}

	// Create the S3 client
	client := s3.NewFromConfig(cfg)

	// 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)
	}
}

// Upload a file to R2
func uploadFile(client *s3.Client, objectKey, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("failed to open file %s: %w", filePath, err)
	}
	defer file.Close()

	_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket: aws.String(r2BucketName),
		Key:    aws.String(objectKey),
		Body:   file,
		ACL:    types.ObjectCannedACLPublicRead, // Optional: Make the file public
	})
	if err != nil {
		return fmt.Errorf("failed to upload file to R2: %w", err)
	}

	fmt.Printf("File %s uploaded to R2 as %s\n", filePath, objectKey)
	return nil
}

// Download a file from R2
func downloadFile(client *s3.Client, objectKey, destPath string) error {
	resp, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
		Bucket: aws.String(r2BucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		return fmt.Errorf("failed to download file from R2: %w", err)
	}
	defer resp.Body.Close()

	outFile, err := os.Create(destPath)
	if err != nil {
		return fmt.Errorf("failed to create file %s: %w", destPath, err)
	}
	defer outFile.Close()

	_, err = outFile.ReadFrom(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to write file to %s: %w", destPath, err)
	}

	fmt.Printf("File %s downloaded from R2 and saved as %s\n", objectKey, destPath)
	return nil
}