Denoでファイルサーバーを書いているのですが、カスタムの404ページを追加するにはどうすれば良いでしょうか?
1 件の回答
これが最適解ではない気もしますが、単純にserveDir
を使用している場合404のときはresponse#statusが404を持っているので、任意のカスタムレスポンスを代わりにreturnすることでカスタム404が使用可能です。
import { serve } from "https://deno.land/std@0.151.0/http/server.ts";
import { serveDir } from "https://deno.land/std@0.151.0/http/file_server.ts";
import {
Status,
STATUS_TEXT,
} from "https://deno.land/std@0.151.0/http/http_status.ts";
serve(async (req) => {
const res = await serveDir(req, {
fsRoot: "./static/",
showDirListing: true,
});
if (res.status === Status.NotFound) {
return new Response("404 not found", {
status: Status.NotFound,
statusText: STATUS_TEXT[Status.NotFound],
headers: {
"content-type": "text/html",
},
});
}
return res;
});