-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathhttp_server_files.ts
43 lines (38 loc) · 1.41 KB
/
http_server_files.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* @title HTTP server: Serving files
* @difficulty intermediate
* @tags cli, deploy
* @run -N -R <url>
* @resource {https://docs.deno.com/api/deno/~/Deno.serve} Doc: Deno.serve
* @resource {https://jsr.io/@std/http#file-server} Doc: @std/http/file-server
* @resource {/examples/http_server} Example: HTTP Server: Hello World
* @group Network
*
* An example of a HTTP server that serves files.
*/
// Import utility methods for serving files with mime types.
import { serveDir, serveFile } from "jsr:@std/http/file-server";
// Here we start a simple server
Deno.serve((req: Request) => {
// Get the path from the url (ie. example.com/whatever -> /whatever)
const pathname = new URL(req.url).pathname;
if (pathname === "/simple_file") {
// In the most basic case we can just call this function with the
// request object and path to the file
return serveFile(req, "./path/to/file.txt");
}
if (pathname.startsWith("/static")) {
// We can also serve a whole directory using the serveDir utility
// method. By default it serves the current directory but this
// can be changed using the "fsRoot" option. We can use the "urlRoot"
// option to strip off the start of the url in the case we don't
// serve the directory at the top level.
return serveDir(req, {
fsRoot: "public",
urlRoot: "static",
});
}
return new Response("404: Not Found", {
status: 404,
});
});