Last active
September 16, 2021 04:03
-
-
Save NotFounds/41530c05c8f14d1c0840b176396aba6a to your computer and use it in GitHub Desktop.
URLPattern example in Deno
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
import { listenAndServe } from "https://deno.land/std@0.107.0/http/server.ts"; | |
const addr = ":8080"; | |
const patternsToHandlers = new Map([ | |
[{ pathname: "/" }, rootHandler], | |
[{ pathname: "/ping" }, pingHandler], | |
[{ pathname: "/user/:id" }, userHandler], | |
]); | |
const routingMap = new Map(); | |
for (const [pathPattern, handler] of patternsToHandlers) { | |
const compiledPattern = new URLPattern(pathPattern); | |
routingMap.set(compiledPattern, handler); | |
} | |
const routingHandler = (request: Request): Response => { | |
for (const [pattern, handler] of routingMap) { | |
const matched = pattern.exec(request.url); | |
if (matched) { | |
return handler(request, matched); | |
} | |
} | |
return new Response(null, { status: 404 }); | |
}; | |
console.log(`HTTP webserver running. Access it at: http://localhost${addr}/`); | |
await listenAndServe(addr, routingHandler); | |
// request handlers | |
function rootHandler(req: Request, matchRes: URLPatternResult | null) { | |
return new Response("Hello, World!", { status: 200 }); | |
} | |
function pingHandler(req: Request, matchRes: URLPatternResult | null) { | |
return new Response("pong", { status: 200 }); | |
} | |
function userHandler(req: Request, matchRes: URLPatternResult | null) { | |
return new Response(`User ID: ${matchRes?.pathname.groups.id}`, { status: 200 }); | |
} |
handler に URLPatternResult が露出してるのあまりイケてない気がするな
URLPattern はあくまで URL の handle しか出来ないので http method と組み合わせて routing する場合は別で分岐が必要
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ref: denoland/deno#11941