denoland / std

The Deno Standard Library
https://jsr.io/@std
MIT License
3k stars 602 forks source link

feat_req(http/routes): add a accept filter #5883

Open lowlighter opened 2 weeks ago

lowlighter commented 2 weeks ago

Is your feature request related to a problem? Please describe.

Current implementation is supporting http method discriminant probably covers most use-case, but there's also one more use-case which I feel like is pretty common is Accept header discriminant.

Sometimes, same route path may serve different content based on Accept headers (for example a nice page for users when text/html is present, and a json object for developers when application/json is passed.

Describe the solution you'd like

Example: sending different format based on requested accept types:

const routes: Route[] = [
  {
    pattern: new URLPattern({ pathname: "/api/foo" }),
    accept: ["application/xml"]
    handler: () => new Response("<foo>bar</foo>"),
  },
  {
    pattern: new URLPattern({ pathname: "/api/foo" }),
    accept: ["application/json"]
    handler: () => new Response('{"foo":{"bar"}}'),
  }
];

Behaviour could be:

Which also means that it's possible to specify the same route multiple time with different accept headers, and possible specify one without if you want a default handler for this route

Describe alternatives you've considered

Not using route or handle in default handler but less elegant

iuioiua commented 2 weeks ago

AFAIK, quite a lot of other routers in the JS ecosystem just match the URL and method. accept header matching can be easily done within the matched route handler.