-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathworker.js
More file actions
61 lines (52 loc) · 1.72 KB
/
worker.js
File metadata and controls
61 lines (52 loc) · 1.72 KB
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
import { getAssetFromKV } from '@cloudflare/kv-asset-handler';
// Worker to serve static assets
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
const url = new URL(event.request.url);
const path = url.pathname;
try {
// Redirect /mac to /mac/ with a 301
if (path === '/mac') {
return Response.redirect(`${url.origin}/mac/`, 301);
}
// For /mac/ path, serve the index.html
if (path === '/mac/') {
const modifiedRequest = new Request(`${url.origin}/mac/index.html`, event.request);
const response = await getAssetFromKV(event, {
mapRequestToAsset: () => modifiedRequest,
cacheControl: {
browserTTL: 31536000, // 1 year
edgeTTL: 86400, // 1 day
},
});
const headers = new Headers(response.headers);
headers.set('Access-Control-Allow-Origin', '*');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: headers,
});
}
// Try to serve static assets from KV normally
const response = await getAssetFromKV(event, {
// Cache static assets
cacheControl: {
browserTTL: 31536000, // 1 year
edgeTTL: 86400, // 1 day
},
});
// Add CORS headers if needed
const headers = new Headers(response.headers);
headers.set('Access-Control-Allow-Origin', '*');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: headers,
});
} catch (e) {
// Return proper 404 for missing assets
return new Response('Not Found', { status: 404 });
}
}