This repository has been archived by the owner on May 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
- Loading branch information
1 parent
0adc9cd
commit 2313da6
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/** | ||
* @title HTTP Server: Serving Files | ||
* @difficulty intermediate | ||
* @tags cli, deploy | ||
* @run --allow-net --allow-read <url> | ||
* @resource {$std/http/mod.ts} Doc: std/http | ||
* @resource {/http-server} Example: HTTP Server: Hello World | ||
* | ||
* An example of a HTTP server that serves files. | ||
*/ | ||
|
||
// Import utility methods for serving files with mime types. | ||
import { serveDir, serveFile } from "$std/http/file_server.ts"; | ||
|
||
// Import the http server from std/http. | ||
import { serve } from "$std/http/server.ts"; | ||
|
||
// Here we start a simple server | ||
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, | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters