File size: 1,686 Bytes
32e4bbf |
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 |
// Example Cloudflare Worker
// This worker demonstrates basic request handling
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// Route: /
if (url.pathname === '/') {
return new Response('Hello from Cloudflare Worker! 🚀', {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
});
}
// Route: /api/time
if (url.pathname === '/api/time') {
return new Response(JSON.stringify({
timestamp: new Date().toISOString(),
timezone: 'UTC'
}), {
headers: {
'Content-Type': 'application/json'
}
});
}
// Route: /api/headers
if (url.pathname === '/api/headers') {
const headers = {};
request.headers.forEach((value, key) => {
headers[key] = value;
});
return new Response(JSON.stringify({
method: request.method,
headers: headers,
cf: request.cf // Cloudflare specific properties
}, null, 2), {
headers: {
'Content-Type': 'application/json'
}
});
}
// Route: /api/echo (POST)
if (url.pathname === '/api/echo' && request.method === 'POST') {
const body = await request.text();
return new Response(JSON.stringify({
message: 'Echo response',
received: body,
length: body.length
}), {
headers: {
'Content-Type': 'application/json'
}
});
}
// 404 Not Found
return new Response('404 Not Found', {
status: 404,
headers: {
'Content-Type': 'text/plain'
}
});
}
}
|