2024-02-22 11:57:31 +01:00
|
|
|
import http from "node:http"
|
2025-09-26 01:53:34 +02:00
|
|
|
import { ServerResponse } from "http"
|
|
|
|
import { createReadStream } from "node:fs"
|
2024-02-22 11:57:31 +01:00
|
|
|
|
2024-06-20 14:22:33 +02:00
|
|
|
export interface Handler {
|
|
|
|
mustMatch: string | RegExp
|
|
|
|
mimetype: string
|
|
|
|
addHeaders?: Record<string, string>
|
2025-09-26 01:53:34 +02:00
|
|
|
/**
|
|
|
|
* IF set, do not write headers and result; only close.
|
|
|
|
* Use this if you want to send binary data
|
|
|
|
*/
|
|
|
|
unmanaged?: boolean
|
2024-06-24 13:11:35 +02:00
|
|
|
handle: (
|
|
|
|
path: string,
|
|
|
|
queryParams: URLSearchParams,
|
2024-07-19 20:43:46 +02:00
|
|
|
req: http.IncomingMessage,
|
2025-09-26 01:53:34 +02:00
|
|
|
body: string | undefined,
|
|
|
|
res: http.ServerResponse
|
2024-06-24 13:11:35 +02:00
|
|
|
) => Promise<string>
|
2024-06-20 14:22:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
class ServerUtils {
|
|
|
|
public static getBody(req: http.IncomingMessage): Promise<string> {
|
|
|
|
return new Promise<string>((resolve) => {
|
2024-06-24 13:11:35 +02:00
|
|
|
let body = ""
|
|
|
|
req.on("data", (chunk) => {
|
|
|
|
body += chunk
|
|
|
|
})
|
|
|
|
req.on("end", () => {
|
2024-06-20 14:22:33 +02:00
|
|
|
resolve(body)
|
2024-06-24 13:11:35 +02:00
|
|
|
})
|
2024-06-20 14:22:33 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-22 11:57:31 +01:00
|
|
|
export class Server {
|
2025-09-26 13:51:12 +02:00
|
|
|
private readonly options: Readonly<{
|
|
|
|
ignorePathPrefix?: ReadonlyArray<string>
|
|
|
|
}>
|
|
|
|
private readonly handlers: ReadonlyArray<Handler>
|
2024-02-22 11:57:31 +01:00
|
|
|
constructor(
|
|
|
|
port: number,
|
|
|
|
options: {
|
|
|
|
ignorePathPrefix?: string[]
|
|
|
|
},
|
2024-06-20 14:22:33 +02:00
|
|
|
handle: Handler[]
|
2024-02-22 11:57:31 +01:00
|
|
|
) {
|
2025-09-26 13:51:12 +02:00
|
|
|
this.options = options
|
|
|
|
|
2024-02-22 11:57:31 +01:00
|
|
|
handle.push({
|
|
|
|
mustMatch: "",
|
|
|
|
mimetype: "text/html",
|
|
|
|
handle: async () => {
|
|
|
|
return `<html><body>Supported endpoints are <ul>${handle
|
|
|
|
.filter((h) => h.mustMatch !== "")
|
|
|
|
.map((h) => {
|
|
|
|
let l = h.mustMatch
|
|
|
|
if (typeof h.mustMatch === "string") {
|
|
|
|
l = `<a href='${l}'>${l}</a>`
|
|
|
|
}
|
|
|
|
return "<li>" + l + "</li>"
|
|
|
|
})
|
|
|
|
.join("")}</ul></body></html>`
|
|
|
|
},
|
|
|
|
})
|
2025-09-26 13:51:12 +02:00
|
|
|
this.handlers = handle
|
2025-10-11 14:03:42 +02:00
|
|
|
http.createServer((req: http.IncomingMessage, res) => this.answerRequest(req, res)).listen(
|
|
|
|
port
|
|
|
|
)
|
2025-09-26 13:51:12 +02:00
|
|
|
console.log(
|
|
|
|
"Server is running on http://127.0.0.1:" + port,
|
|
|
|
". Supported endpoints are: " + handle.map((h) => h.mustMatch).join(", ")
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
private async answerRequest(req: http.IncomingMessage, res: ServerResponse) {
|
|
|
|
try {
|
|
|
|
const url = new URL(`http://127.0.0.1/` + req.url)
|
|
|
|
let path = url.pathname
|
|
|
|
while (path.startsWith("/")) {
|
|
|
|
path = path.substring(1)
|
|
|
|
}
|
|
|
|
console.log(
|
|
|
|
req.method + " " + req.url,
|
|
|
|
"from:",
|
|
|
|
req.headers.origin,
|
|
|
|
new Date().toISOString(),
|
2025-10-11 14:03:42 +02:00
|
|
|
path
|
2025-09-26 13:51:12 +02:00
|
|
|
)
|
|
|
|
if (this.options?.ignorePathPrefix) {
|
|
|
|
for (const toIgnore of this.options.ignorePathPrefix) {
|
|
|
|
if (path.startsWith(toIgnore)) {
|
|
|
|
path = path.substring(toIgnore.length + 1)
|
|
|
|
break
|
2024-02-22 11:57:31 +01:00
|
|
|
}
|
|
|
|
}
|
2025-09-26 13:51:12 +02:00
|
|
|
}
|
|
|
|
const handler = this.handlers.find((h) => {
|
|
|
|
if (typeof h.mustMatch === "string") {
|
|
|
|
return h.mustMatch === path
|
|
|
|
}
|
|
|
|
if (path.match(h.mustMatch)) {
|
|
|
|
return true
|
2024-02-22 11:57:31 +01:00
|
|
|
}
|
2025-09-26 13:51:12 +02:00
|
|
|
})
|
2024-02-22 11:57:31 +01:00
|
|
|
|
2025-09-26 13:51:12 +02:00
|
|
|
if (handler === undefined || handler === null) {
|
|
|
|
res.writeHead(404, { "Content-Type": "text/html" })
|
|
|
|
res.write("<html><body><p>Not found...</p></body></html>")
|
|
|
|
res.end()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
res.setHeader(
|
|
|
|
"Access-Control-Allow-Headers",
|
2025-10-11 14:03:42 +02:00
|
|
|
"Origin, X-Requested-With, Content-Type, Accept"
|
2025-09-26 13:51:12 +02:00
|
|
|
)
|
|
|
|
res.setHeader("Access-Control-Allow-Origin", req.headers.origin ?? "*")
|
|
|
|
if (req.method === "OPTIONS") {
|
2025-10-11 14:03:42 +02:00
|
|
|
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, UPDATE")
|
2025-09-26 13:51:12 +02:00
|
|
|
res.writeHead(204, { "Content-Type": handler.mimetype })
|
|
|
|
res.end()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
let body: string | undefined = undefined
|
|
|
|
if (req.method === "POST" || req.method === "UPDATE") {
|
|
|
|
body = await ServerUtils.getBody(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === "DELETE") {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const task = handler.handle(path, url.searchParams, req, body, res)
|
|
|
|
if (handler.unmanaged) {
|
2024-02-22 11:57:31 +01:00
|
|
|
return
|
|
|
|
}
|
2025-09-26 13:51:12 +02:00
|
|
|
const result = await task
|
|
|
|
if (result === undefined) {
|
|
|
|
res.writeHead(500)
|
|
|
|
res.write("Could not fetch this website, probably blocked by them")
|
|
|
|
res.end()
|
2024-02-22 11:57:31 +01:00
|
|
|
return
|
|
|
|
}
|
2025-09-26 13:51:12 +02:00
|
|
|
if (typeof result !== "string") {
|
|
|
|
console.error(
|
|
|
|
"Internal server error: handling",
|
|
|
|
url,
|
|
|
|
"resulted in a ",
|
|
|
|
typeof result,
|
|
|
|
" instead of a string:",
|
2025-10-11 14:03:42 +02:00
|
|
|
result
|
2025-09-26 13:51:12 +02:00
|
|
|
)
|
|
|
|
}
|
2024-02-22 11:57:31 +01:00
|
|
|
|
2025-09-26 13:51:12 +02:00
|
|
|
const extraHeaders = handler.addHeaders ?? {}
|
|
|
|
res.writeHead(200, { "Content-Type": handler.mimetype, ...extraHeaders })
|
|
|
|
res.write("" + result)
|
|
|
|
res.end()
|
2024-02-22 11:57:31 +01:00
|
|
|
} catch (e) {
|
2025-09-26 13:51:12 +02:00
|
|
|
console.error("Could not handle request:", e)
|
|
|
|
res.writeHead(500)
|
|
|
|
res.write("Internal server error - something went wrong:")
|
|
|
|
res.write(e.toString())
|
2024-02-22 11:57:31 +01:00
|
|
|
res.end()
|
|
|
|
}
|
2025-09-26 13:51:12 +02:00
|
|
|
} catch (e) {
|
|
|
|
console.error("FATAL:", e)
|
|
|
|
res.end()
|
|
|
|
}
|
2024-02-22 11:57:31 +01:00
|
|
|
}
|
2025-09-26 01:53:34 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Sends a file straight from disk.
|
|
|
|
* Assumes that headers have been set on res
|
|
|
|
* @param path
|
|
|
|
* @param res
|
|
|
|
*/
|
2025-10-11 14:03:42 +02:00
|
|
|
public static sendFile(path: string, res: ServerResponse) {
|
|
|
|
createReadStream(path).pipe(res)
|
2025-09-26 01:53:34 +02:00
|
|
|
}
|
2024-02-22 11:57:31 +01:00
|
|
|
}
|