Tianhe Gao

Cloudflare 通过 Workers 访问 R2 中存储的文件

代码在 tianheg/cloudflare/r2 。文档 R2 get started guide

wrangler.toml

    name = "r2"
    main = "src/index.js"
    compatibility_date = "2022-08-18"

    account_id = "PLACE YOUR ACCOUNT ID" # at workers page
    workers_dev = true

    [[r2_buckets]]
    binding = 'MY_BUCKET' # <~ valid JavaScript variable name
    bucket_name = 'cloudflare'

index.js

 1    const ALLOW_LIST = ['surplus-value-051.mp3'];
 2
 3    // Check requests for a pre-shared secret
 4    const hasValidHeader = (request, env) => {
 5      return request.headers.get('X-Custom-Auth-Key') === env.AUTH_KEY_SECRET;
 6    };
 7
 8    function authorizeRequest(request, env, key) {
 9      switch (request.method) {
10        case 'PUT':
11        case 'DELETE':
12          return hasValidHeader(request, env);
13        case 'GET':
14          return ALLOW_LIST.includes(key);
15        default:
16          return false;
17      }
18    }
19
20    export default {
21      async fetch(request, env) {
22        const url = new URL(request.url);
23        const key = url.pathname.slice(1);
24
25        if (!authorizeRequest(request, env, key)) {
26          return new Response('Forbidden', { status: 403 });
27        }
28
29        switch (request.method) {
30          case 'PUT':
31            await env.MY_BUCKET.put(key, request.body);
32            return new Response(`Put ${key} successfully!`);
33          case 'GET':
34            const object = await env.MY_BUCKET.get(key);
35
36            if (object === null) {
37              return new Response('Object Not Found', { status: 404 });
38            }
39
40            const headers = new Headers();
41            object.writeHttpMetadata(headers);
42            headers.set('etag', object.httpEtag);
43
44            return new Response(object.body, {
45              headers,
46            });
47          case 'DELETE':
48            await env.MY_BUCKET.delete(key);
49            return new Response('Deleted!');
50
51          default:
52            return new Response('Method Not Allowed', {
53              status: 405,
54              headers: {
55                Allow: 'PUT, GET, DELETE',
56              },
57            });
58        }
59      },
60    };

No notes link to this note

Welcome to tell me your thoughts via "email"
UP