/serve-router

tiny router library that routes for your web standard http server

Primary LanguageTypeScriptMIT LicenseMIT

serve-router

a small express like library that routes for your http server
build for deno's serve() api, which is compatible with some serverless platform
e.g. Cloudflare Workers
see: https://deno.com/manual/runtime/http_server_apis

usage

we use the latest version of path-to-regexp to match, which is different from what express depends
for example, you can use /** to match any path in express, but should use /(.*) here
you may want to test the match syntax via https://forbeslindesay.github.io/express-route-tester/

// use Deno
import { serve } from "https://deno.land/std@0.188.0/http/server.ts";
import App from "https://esm.sh/serve-router@latest";

// use Node.js >= 16
import { serve } from "serve-router/node";
import App from "serve-router";

const app = App();

app.get("/", (_req) => new Response("Hello, world!"));

app.get("/headers", (req: Request) => Response.json(Object.fromEntries(req.headers.entries())));

app.get<{ name: string }>("/user/:name", (_req, { params }) => {
    return new Response(`Hello, ${params.name}`);
});

app.post("/post", async (req) => {
    const json = await req.json();
    return Response.json(json);
});

app.route("/api")
    // for /api
    .get("", () => new Response("api"))
    // for /api/one
    .get("/one", () => new Response("one"))
    // for /api/two
    .get("/two", () => new Response("two"));

serve(app.export);

build

git clone https://github.com/YieldRay/serve-router.git
cd serve-router

pnpm install
mkdir -p src/path-to-regexp
curl -fSskL https://github.com/pillarjs/path-to-regexp/raw/master/src/index.ts -o src/path-to-regexp/index.ts

pnpm run build