// 导入 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 { // 获取请求的路径 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( `

404 Not Found

The requested URL ${req.url} was not found on this server.

`, 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); }