-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
84 lines (70 loc) · 2.37 KB
/
worker.js
File metadata and controls
84 lines (70 loc) · 2.37 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { getHTML } from './layout.js';
export default {
async fetch(request, env, ctx) {
try {
const url = new URL(request.url);
// Serve the counter image
if (url.pathname === '/counter.gif') {
let count = '000001';
try {
const storedCount = await env.VISITOR_COUNT.get('count');
if (storedCount) {
count = storedCount.padStart(6, '0');
}
} catch (e) {
console.error('KV read error:', e);
}
const svg = generateCounterSVG(count);
return new Response(svg, {
headers: {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'no-cache',
},
});
}
// Serve the main HTML page
if (url.pathname === '/' || url.pathname === '/index.html') {
let count = 1;
try {
// Get and increment counter
const storedCount = await env.VISITOR_COUNT.get('count');
if (storedCount) {
count = parseInt(storedCount) + 1;
} else {
count = 1;
}
// Save the incremented count (non-blocking)
ctx.waitUntil(env.VISITOR_COUNT.put('count', count.toString()));
} catch (e) {
console.error('KV operation error:', e);
}
const html = getHTML(count);
return new Response(html, {
headers: {
'Content-Type': 'text/html;charset=UTF-8',
},
});
}
return new Response('Not Found', { status: 404 });
} catch (error) {
console.error('Worker error:', error);
return new Response('Internal Server Error: ' + error.message, { status: 500 });
}
},
};
function generateCounterSVG(count) {
const digits = count.toString().padStart(6, '0').split('');
const width = digits.length * 15;
let digitBoxes = '';
digits.forEach((digit, i) => {
const x = i * 15;
digitBoxes += `
<rect x="${x}" y="0" width="14" height="20" fill="#000000" stroke="#00ff00" stroke-width="1"/>
<text x="${x + 7}" y="15" font-family="Courier, monospace" font-size="14" fill="#00ff00" text-anchor="middle" font-weight="bold">${digit}</text>
`;
});
return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="20">
${digitBoxes}
</svg>`;
}