import http from "http";
type Handler = (
req: http.IncomingMessage,
res: http.ServerResponse,
url: URL
) => void | Promise<void>;
const routes = new Map<string, Handler>([
["GET /", homeHandler],
["GET /users", getUsersHandler],
["POST /users", createUserHandler],
]);
const server = http.createServer(async (req, res) => {
const method = req.method ?? "GET";
const url = new URL(
req.url ?? "/",
`http://${req.headers.host}`
);
const key = `${method} ${url.pathname}`;
const handler = routes.get(key);
if (!handler) {
res.writeHead(404);
res.end("Not Found");
return;
}
await handler(req, res, url);
});
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme