2023-06-29 19:18:52 +00:00
|
|
|
import RestResponse from "./RestResponse.ts";
|
|
|
|
import { Handler } from "./Router.ts";
|
|
|
|
|
|
|
|
export default function staticHandler(path: string): Handler {
|
|
|
|
return {
|
|
|
|
async handle(req) {
|
|
|
|
try {
|
2023-06-30 00:37:07 +00:00
|
|
|
const realPath = await Deno.realPath(`${path}/${req.url}`);
|
2023-06-30 21:49:40 +00:00
|
|
|
const stream = await Deno.open(realPath, { read: true });
|
2023-06-30 00:37:07 +00:00
|
|
|
const i = realPath.lastIndexOf('.');
|
|
|
|
const res = new RestResponse().body(stream.readable);
|
2023-06-30 21:49:40 +00:00
|
|
|
await stream.read(new Uint8Array(1));
|
|
|
|
await stream.seek(0, Deno.SeekMode.Start);
|
|
|
|
|
2023-06-30 23:00:59 +00:00
|
|
|
if (i >= 0) return res.contentType(realPath.substring(i + 1));
|
|
|
|
else return res;
|
2023-06-29 19:18:52 +00:00
|
|
|
}
|
2023-06-30 00:37:07 +00:00
|
|
|
catch (e) {
|
2023-06-30 23:00:59 +00:00
|
|
|
console.error(e);
|
2023-06-29 19:18:52 +00:00
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|