Refactor MIME type helper function and move outside server block
This commit is contained in:
59
server.ts
59
server.ts
@@ -1,39 +1,38 @@
|
|||||||
// server.ts
|
// server.ts
|
||||||
|
|
||||||
|
// Helper function to get MIME type
|
||||||
|
function getMimeType(filename: string): string {
|
||||||
|
switch (filename.split(".").pop()?.toLowerCase()) {
|
||||||
|
case "js":
|
||||||
|
return "application/javascript";
|
||||||
|
case "ts":
|
||||||
|
return "application/javascript";
|
||||||
|
case "css":
|
||||||
|
return "text/css";
|
||||||
|
case "html":
|
||||||
|
return "text/html";
|
||||||
|
case "json":
|
||||||
|
return "application/json";
|
||||||
|
case "png":
|
||||||
|
return "image/png";
|
||||||
|
case "jpg":
|
||||||
|
case "jpeg":
|
||||||
|
return "image/jpeg";
|
||||||
|
case "svg":
|
||||||
|
return "image/svg+xml";
|
||||||
|
case "ico":
|
||||||
|
return "image/x-icon";
|
||||||
|
default:
|
||||||
|
return "text/plain";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const server = Bun.serve({
|
const server = Bun.serve({
|
||||||
port: 5173,
|
port: 5173,
|
||||||
async fetch(req) {
|
async fetch(req) {
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const pathname = url.pathname;
|
const pathname = url.pathname;
|
||||||
|
|
||||||
// Helper function to get MIME type
|
|
||||||
function getMimeType(filename: string): string {
|
|
||||||
const ext = filename.split(".").pop()?.toLowerCase();
|
|
||||||
switch (ext) {
|
|
||||||
case "js":
|
|
||||||
return "application/javascript";
|
|
||||||
case "ts":
|
|
||||||
return "application/javascript";
|
|
||||||
case "css":
|
|
||||||
return "text/css";
|
|
||||||
case "html":
|
|
||||||
return "text/html";
|
|
||||||
case "json":
|
|
||||||
return "application/json";
|
|
||||||
case "png":
|
|
||||||
return "image/png";
|
|
||||||
case "jpg":
|
|
||||||
case "jpeg":
|
|
||||||
return "image/jpeg";
|
|
||||||
case "svg":
|
|
||||||
return "image/svg+xml";
|
|
||||||
case "ico":
|
|
||||||
return "image/x-icon";
|
|
||||||
default:
|
|
||||||
return "text/plain";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serve root as index.html
|
// Serve root as index.html
|
||||||
if (pathname === "/")
|
if (pathname === "/")
|
||||||
try {
|
try {
|
||||||
@@ -56,11 +55,9 @@ const server = Bun.serve({
|
|||||||
if (!exists)
|
if (!exists)
|
||||||
return new Response(`File not found: ${filename}`, { status: 404 });
|
return new Response(`File not found: ${filename}`, { status: 404 });
|
||||||
|
|
||||||
const mimeType = getMimeType(filename);
|
|
||||||
|
|
||||||
return new Response(file, {
|
return new Response(file, {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": mimeType,
|
"Content-Type": getMimeType(filename),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user