Deno_SetUpLocalWebServer
まだ理解が十分ではない
とりあえず「ただローカルサーバーを立てるだけ」ならできるようになった
code:server.ts
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".json": "application/json",
".svg": "image/svg+xml",
// 読み取りたいMIMEタイプはここに追記
};
const getMimeType = (pathname: string) => {
let result = '';
for (const property in mime) {
if (pathname.endsWith(property)) result = mimeproperty; }
return result || 'text/plain';
}
function createHandler(indexHtml: string | URL) {
const handler = async (request: Request): Promise<Response> => {
console.log("Request:", request.method, request.url);
const { pathname, search } = new URL(request.url);
if (pathname === '/') {
const html = Deno.readFileSync(indexHtml);
return new Response(html, {
headers: { 'Content-Type': 'text/html; charset=utf-8' },
});
} else if (request.method === "GET") {
const data = JSON.stringify({ pathname, search }, null, 2);
console.log("Request Data:", data);
const type = getMimeType(pathname);
return new Response(Deno.readFileSync(pathname.substring(1)), {
headers: { 'Content-Type': ${type}; charset=utf-8 },
});
} else if (request.method === "POST") {
const payload = await request.text();
const data = JSON.stringify({ pathname, payload }, null, 2);
console.log("Request Data:", data);
return new Response(data, {
headers: { "Content-Type": "application/json" },
});
}
return new Response("Not Found", { status: 404 });
};
return handler;
}
/**
* @param port ポート番号
* @param html index.htmlのパス
*/
export function setServer(port: number, html: string) {
Deno.serve({ port }, createHandler(html));
}