Static site hosting via tangled
1import express from "express";
2import yargs from "yargs";
3import { Handler } from "./handler.js";
4import { Config } from "./config.js";
5
6class Server {
7 constructor({ handler }) {
8 this.handler = handler;
9
10 this.app = express();
11
12 this.app.get("/{*any}", async (req, res) => {
13 const host = req.hostname;
14 const path = req.path;
15 const { status, content, contentType } = await this.handler.handleRequest(
16 {
17 host,
18 path,
19 }
20 );
21 res.status(status).set("Content-Type", contentType).send(content);
22 });
23 }
24
25 async start({ port }) {
26 this.app.listen(port, () => {
27 console.log(`Server is running on port ${port}`);
28 });
29 this.app.on("error", (error) => {
30 console.error("Server error:", error);
31 });
32 }
33}
34
35async function main() {
36 const args = yargs(process.argv.slice(2)).parse();
37 const port = args.port ?? args.p ?? 3000;
38 const configFilepath = args.config || "config.json";
39 const config = await Config.fromFile(configFilepath);
40 const handler = await Handler.fromConfig(config);
41 const server = new Server({
42 handler,
43 });
44 await server.start({ port });
45}
46
47main();