Skip to content

Instantly share code, notes, and snippets.

@queercat
Created October 30, 2024 19:09
Show Gist options
  • Select an option

  • Save queercat/fcfb4cef8bd22109565432e33d368bb3 to your computer and use it in GitHub Desktop.

Select an option

Save queercat/fcfb4cef8bd22109565432e33d368bb3 to your computer and use it in GitHub Desktop.
Minimal HTTP framework in Deno.
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