-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
67 lines (61 loc) · 2.12 KB
/
main.ts
File metadata and controls
67 lines (61 loc) · 2.12 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
/// <reference lib="deno.unstable" />
const KV_KEY_FEEDS = ['feeds'];
const config = {
"host": "0.0.0.0",
"port": 8291
};
const api_to_mode = {
'~getfeeds': 'get',
'~feed': 'hit'
}
function extname(path: string) {
const segs = path.split('.');
if (segs.length === 1) return '';
return segs[segs.length - 1];
}
const Mimetype = {
'html': 'text/html;charset=utf-8',
'svg': 'image/svg+xml;charset=utf-8',
'css': 'text/css;charset=utf-8',
'js': 'text/javascript;charset=utf-8',
'json': 'text/json;charset=utf-8',
'ico': 'image/vnd.microsoft.icon'
};
Deno.serve({
hostname: config.host,
port: config.port
}, async function (request: Request) {
const url = new URL(request.url);
let path = url.pathname.slice(1);
if (path === '')
path = 'index.html';
if (path === 'nait-fun.html')
return new Response(null, {
status: 301,
headers: { 'Location': '/' }
});
if (path.startsWith('~')) {
const mode = api_to_mode[path as keyof typeof api_to_mode];
if (mode === undefined)
return new Response(null, { status: 400 });
const kv = await Deno.openKv();
const entry_feeds = await kv.get<number>(KV_KEY_FEEDS);
let feeds;
if (entry_feeds.value === null)
await kv.set(KV_KEY_FEEDS, feeds = 0);
else
feeds = entry_feeds.value;
switch (mode) {
case 'hit':
await kv.set(KV_KEY_FEEDS, feeds += 1);
return new Response(null, { status: 206, headers: { 'Access-Control-Allow-Origin': '*' } });
case 'get':
return new Response(JSON.stringify({ 'value': feeds }), {
headers: { 'Content-Type': Mimetype['json'], 'Access-Control-Allow-Origin': '*' }
});
}
}
return fetch(new URL(path, import.meta.url)).then(r => r.body).then(stream => new Response(stream, {
headers: { 'Content-Type': Mimetype[extname(path)] || 'text/plain', 'Access-Control-Allow-Origin': '*' }
})).catch(_ => new Response('not found', { status: 404 }));
});