1
0
Fork 0
mirror of https://github.com/kou029w/quot.git synced 2025-01-19 00:18:09 +00:00
quot/app/src/server.ts

55 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-08-23 09:01:47 +09:00
import type { AddressInfo } from "node:net";
import http from "node:http";
import fs from "node:fs";
import esbuild from "esbuild";
async function main() {
const port = Number(process.env.PORT ?? "8080");
2022-08-28 23:27:02 +09:00
const apiUrl = process.env.QUOT_API_URL || "http://127.0.0.1:3000/";
2022-08-23 09:01:47 +09:00
const publicDir = __dirname;
const htmlPath = `${publicDir}/index.html`;
const scriptPath = `${publicDir}/index.ts`;
const result = await esbuild.serve(
{
host: "127.0.0.1",
servedir: publicDir,
},
{
bundle: true,
minify: true,
entryPoints: [scriptPath],
}
);
const handler: http.RequestListener = (req, res) => {
2022-08-28 19:57:18 +09:00
const api = req.url?.startsWith("/api/") && new URL(apiUrl);
2022-08-23 09:01:47 +09:00
const options = {
2022-08-28 19:57:18 +09:00
hostname: /**/ api ? api.hostname /* */ : result.host,
port: /* */ api ? api.port /* */ : result.port,
path: /* */ api ? req.url?.slice("/api".length) /**/ : req.url,
2022-08-23 09:01:47 +09:00
method: req.method,
headers: req.headers,
};
const proxyReq = http.request(options, (proxyRes) => {
2022-08-28 19:57:18 +09:00
if (api || proxyRes.statusCode === 200) {
res.writeHead(proxyRes.statusCode ?? 500, proxyRes.headers);
2022-08-23 09:01:47 +09:00
proxyRes.pipe(res);
} else {
res.writeHead(200, { "Content-Type": "text/html" });
fs.createReadStream(htmlPath).pipe(res);
}
});
req.pipe(proxyReq);
};
const server = http.createServer(handler).listen(port);
const address = server.address() as AddressInfo;
console.log(`http://0.0.0.0:${address.port}`);
}
main();