Files
blog/deploy.ts
T
2024-07-11 08:59:32 +08:00

70 lines
1.9 KiB
TypeScript

// 导入 Deno Deploy 所需的模块
import {
serve,
ServerRequest,
Response,
createHtmlResponse,
createResponse,
} from "https://deno.land/x/deploy@v1.10.0/mod.ts";
import { exists } from "https://deno.land/std/fs/mod.ts";
import { join } from "https://deno.land/std/path/mod.ts";
const publicPath = "./public";
async function serveStatic(req: ServerRequest): Promise<Response> {
// 获取请求的路径
const url = new URL(req.url);
let filePath = join(publicPath, url.pathname);
// 如果请求的是根路径,则返回 index.html
if (url.pathname === "/") {
filePath = join(publicPath, "index.html");
}
// 检查文件是否存在
if (await exists(filePath)) {
// 返回静态文件
const content = await Deno.readFile(filePath);
return createResponse(200, content, {
"Content-Type": contentType(filePath),
});
} else {
// 如果文件不存在,返回 404 错误页面
return createHtmlResponse(
`<html><body><h1>404 Not Found</h1><p>The requested URL ${req.url} was not found on this server.</p></body></html>`,
404
);
}
}
function contentType(filePath: string): string {
// 根据文件后缀返回对应的 Content-Type
const ext = filePath.split(".").pop();
switch (ext) {
case "html":
return "text/html";
case "css":
return "text/css";
case "js":
return "application/javascript";
case "png":
return "image/png";
case "jpg":
case "jpeg":
return "image/jpeg";
case "gif":
return "image/gif";
default:
return "text/plain";
}
}
// 创建一个服务器并监听请求
const server = serve({ port: 8080 });
console.log("Server is running at http://localhost:8080");
for await (const req of server) {
const response = await serveStatic(req);
await req.respond(response);
}