const http = require('http');
|
|
function json(res, status, body) {
|
const data = typeof body === 'string' ? body : JSON.stringify(body);
|
res.writeHead(status, {
|
'Content-Type': 'application/json; charset=utf-8',
|
'Access-Control-Allow-Origin': '*',
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
'Access-Control-Allow-Headers': 'Content-Type'
|
});
|
res.end(typeof body === 'string' ? body : JSON.stringify(body, null, 2));
|
}
|
|
function notFound(res) {
|
json(res, 404, { error: 'Not Found' });
|
}
|
|
function startHttpApi({ host = '0.0.0.0', port = 8080, getDevices, getAllData, getDataBySerial }) {
|
const server = http.createServer((req, res) => {
|
if (req.method === 'OPTIONS') {
|
res.writeHead(204, {
|
'Access-Control-Allow-Origin': '*',
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
'Access-Control-Allow-Headers': 'Content-Type'
|
});
|
return res.end();
|
}
|
|
const url = new URL(req.url, `http://${req.headers.host}`);
|
const path = url.pathname;
|
|
// 路由
|
if (req.method === 'GET' && path === '/api/devices') {
|
const list = getDevices();
|
return json(res, 200, { devices: list });
|
}
|
|
if (req.method === 'GET' && path === '/api/data') {
|
const all = getAllData();
|
return json(res, 200, all);
|
}
|
|
if (req.method === 'GET' && path.startsWith('/api/data/')) {
|
const serial = decodeURIComponent(path.substring('/api/data/'.length));
|
if (!serial) return notFound(res);
|
const data = getDataBySerial(serial);
|
if (!data) return notFound(res);
|
return json(res, 200, data);
|
}
|
|
return notFound(res);
|
});
|
|
server.listen(port, host, () => {
|
console.log(`🌐 HTTP API 已启动: http://${host}:${port}`);
|
console.log(' • GET /api/devices → 已连接设备序列号列表');
|
console.log(' • GET /api/data → 全部设备最新解析数据');
|
console.log(' • GET /api/data/:serial → 指定设备最新解析数据');
|
});
|
|
return server;
|
}
|
|
module.exports = { startHttpApi };
|