Class Router
Matching compares path segments rather than running a regular expression. For a path that is already a list of segments, comparing them is both the direct implementation and the faster one, and it needs no pattern engine at all.
public class Api implements Worker {
private static final Router ROUTES = Router.create()
.get("/health", (request, path, env, ctx) -> Bytebox.response("ok"))
.get("/users/:id", (request, path, env, ctx) -> Bytebox.response(path.get("id")))
.post("/users", Api::create)
.notFound((request, path, env, ctx) -> Bytebox.response("no such route", 404));
@Override
public Response fetch(Request request, Env env, ExecutionCtx ctx) {
return ROUTES.route(request, env, ctx);
}
}
A pattern is a path with two kinds of placeholder. :name matches one segment and captures
it. A trailing * matches the rest of the path and captures it as *. Everything else
is compared literally.
Routes are tried in the order they were added, so a literal declared before a parameter wins over it. That is the order the code reads in, which is the order a reader expects.
- Since:
- 1.0.0
-
Method Summary
Modifier and TypeMethodDescriptionAdds a route for every method.static Routercreate()Returns a new router with no routes.Adds aDELETEroute.Adds aGETroute.Sets what answers a request no route matched.Adds a route.Adds aPATCHroute.Adds aPOSTroute.Adds aPUTroute.route(Request request, Env env, ExecutionCtx ctx) Routes a request.Adds a filter, which sees every request before the route does.
-
Method Details
-
create
Returns a new router with no routes.- Returns:
- a new router with no routes
-
on
Adds a route.- Parameters:
method- the HTTP method, uppercase, or*for anypattern- the path patternroute- what answers it- Returns:
- this router
-
get
Adds aGETroute.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
post
Adds aPOSTroute.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
put
Adds aPUTroute.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
patch
Adds aPATCHroute.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
delete
Adds aDELETEroute.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
any
Adds a route for every method.- Parameters:
pattern- the path patternroute- what answers it- Returns:
- this router
-
notFound
Sets what answers a request no route matched.- Parameters:
route- what answers it- Returns:
- this router
-
use
Adds a filter, which sees every request before the route does.Run in the order added, outermost first. A filter that answers rather than continuing is what makes authentication and rate limiting work.
- Parameters:
filter- the filter- Returns:
- this router
-
route
Routes a request.- Parameters:
request- the requestenv- the bindingsctx- the invocation context- Returns:
- whatever answered it
-