Created
October 30, 2024 19:09
-
-
Save queercat/fcfb4cef8bd22109565432e33d368bb3 to your computer and use it in GitHub Desktop.
Minimal HTTP framework in Deno.
This file contains hidden or 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
| interface route { | |
| path: string | |
| body: (path: string, values: Record<string, string>) => Promise<string | object | number> | string | object | number | |
| } | |
| const routes: route[] = [ | |
| { | |
| path: "/resource/:value:", | |
| body: (_, values) => { | |
| return values.value | |
| } | |
| } | |
| ] | |
| const route = async (path: string): Promise<Response> => { | |
| const transformedRoutes = routes.map((route) => { | |
| const path = route.path.replace(/\/:([^:]+):/g, "/(?<$1>[^/]+)\/?") | |
| return {path: new RegExp(`^${path}$`), body: route | |
| .body} | |
| }) | |
| for (const route of transformedRoutes) { | |
| const match = path.match(route.path) | |
| if (match) { | |
| const values = match.groups | |
| const body = await route.body(path, values || {}) | |
| return new Response(JSON.stringify(body), {status: 200}) | |
| } | |
| } | |
| return new Response("Not found", {status: 404}) | |
| } | |
| if (import.meta.main) { | |
| Deno.serve((req) => { | |
| return route(new URL(req.url).pathname) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment