file server content type headers
This commit is contained in:
parent
3b1a969145
commit
fcba2014c2
@ -73,6 +73,11 @@ router.serveDirectory('dirWithIndexHtml', '/indexes', {showIndex: true});
|
||||
|
||||
### File-based Routing
|
||||
|
||||
**Note:** _This is an experimental feature and may change in the future.
|
||||
Currently, JSR does not support dynamic imports for external modules in Deno. In
|
||||
order to use this feature, you will need to install as an HTTP module (available
|
||||
soon)._
|
||||
|
||||
```ts
|
||||
import { FileRouter } from "@bearmetal/router";
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@bearmetal/router",
|
||||
"description": "A simple router for Deno",
|
||||
"version": "0.2.3-b",
|
||||
"version": "0.2.4",
|
||||
"stable": true,
|
||||
"files": [
|
||||
"mod.ts",
|
||||
|
@ -6,6 +6,7 @@ import type {
|
||||
RouteConfigurator,
|
||||
RouterContext,
|
||||
} from "./types.ts";
|
||||
import { getContentTypeByExtension } from "./util/contentType.ts";
|
||||
import { NotFound } from "./util/response.ts";
|
||||
|
||||
/**
|
||||
@ -392,7 +393,9 @@ export class Router {
|
||||
|
||||
try {
|
||||
const file = await Deno.readFile(normalizedPath);
|
||||
return new Response(file);
|
||||
const filetype = normalizedPath.split(".")[1];
|
||||
const contentType = getContentTypeByExtension(filetype);
|
||||
return new Response(file, { headers: { "Content-Type": contentType } });
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return showIndex ? generateIndex(normalizedPath) : NotFound();
|
||||
|
26
util/contentType.ts
Executable file
26
util/contentType.ts
Executable file
@ -0,0 +1,26 @@
|
||||
export function getContentTypeByExtension(extension: string) {
|
||||
switch (extension) {
|
||||
case "html":
|
||||
case "htm":
|
||||
return "text/html";
|
||||
case "css":
|
||||
return "text/css";
|
||||
case "js":
|
||||
return "text/javascript";
|
||||
case "json":
|
||||
return "application/json";
|
||||
case "png":
|
||||
return "image/png";
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
return "image/jpeg";
|
||||
case "gif":
|
||||
return "image/gif";
|
||||
case "svg":
|
||||
return "image/svg+xml";
|
||||
case "txt":
|
||||
return "text/plain";
|
||||
default:
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user