forked from xixu-me/xget
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (68 loc) · 2.28 KB
/
Copy pathserver.js
File metadata and controls
78 lines (68 loc) · 2.28 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
import express from 'express';
import handler from './api/[...path].js';
import healthHandler from './api/health.js';
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON bodies
app.use(express.json());
app.use(express.raw({ type: 'application/octet-stream', limit: '50mb' }));
// Health endpoint
app.get('/api/health', async (req, res) => {
try {
const request = new Request(`http://localhost:${PORT}${req.url}`, {
method: req.method,
headers: req.headers
});
const response = await healthHandler(request);
res.status(response.status);
response.headers.forEach((value, key) => {
res.set(key, value);
});
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
res.json(await response.json());
} else {
res.send(await response.text());
}
} catch (error) {
console.error('Health check error:', error);
res.status(500).json({ error: 'Health check failed' });
}
});
// Main handler for all other routes
app.use('*', async (req, res) => {
try {
const request = new Request(`http://localhost:${PORT}${req.originalUrl}`, {
method: req.method,
headers: req.headers,
body: req.method !== 'GET' && req.method !== 'HEAD' ? req.body : undefined
});
const response = await handler(request);
res.status(response.status);
response.headers.forEach((value, key) => {
res.set(key, value);
});
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
res.json(await response.json());
} else if (response.body) {
// Handle binary data
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
res.send(buffer);
} else {
res.send(await response.text());
}
} catch (error) {
console.error('Request handler error:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message,
timestamp: new Date().toISOString()
});
}
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`🚀 Xget server running on port ${PORT}`);
console.log(`📡 Health check: http://localhost:${PORT}/api/health`);
});