vibe.d beta banner
get vibe.d
0.10.0

Asynchronous I/O that doesn’t get in your way, written in D

Class URLRouter

Routes HTTP requests based on the request method and URL.

class URLRouter
  : HTTPServerRequestHandler ;

Routes are matched using a special URL match string that supports two forms of placeholders. See the sections below for more details.

Registered routes are matched according to the same sequence as initially specified using match, get, post etc. Matching ends as soon as a route handler writes a response using res.writeBody() or similar means. If no route matches or if no route handler writes a response, the router will simply not handle the request and the HTTP server will automatically generate a 404 error.

Constructors

NameDescription
this (prefix)

Properties

NameTypeDescription
enableRootDir[set] boolControls the computation of the "routerRootDir" parameter.
prefix[get] stringSets a common prefix for all registered routes.

Methods

NameDescription
any (url_match, handler) Adds a new route for requests matching the specified pattern, regardless of their HTTP verb.
delete_ (url_match, handler) Adds a new route for DELETE requests matching the specified pattern.
get (url_match, handler) Adds a new route for GET requests matching the specified pattern.
getAllRoutes () Returns all registered routes as const AA
handlerDelegate (handler)
handleRequest (req, res) Handles a HTTP request by dispatching it to the registered route handlers.
match (method, path, handler) Adds a new route for requests matching the specified HTTP method and pattern.
patch (url_match, handler) Adds a new route for PATCH requests matching the specified pattern.
post (url_match, handler) Adds a new route for POST requests matching the specified pattern.
put (url_match, handler) Adds a new route for PUT requests matching the specified pattern.
rebuild () Rebuilds the internal matching structures to account for newly added routes.
route (path) Returns a single route handle to conveniently register multiple methods.

Match patterns

Match patterns are character sequences that can optionally contain placeholders or raw wildcards ("*"). Raw wild cards match any character sequence, while placeholders match only sequences containing no slash ("/") characters.

Placeholders are started using a colon (":") and are directly followed by their name. The first "/" character (or the end of the match string) denotes the end of the placeholder name. The part of the string that matches a placeholder will be stored in the HTTPServerRequest.params map using the placeholder name as the key.

Match strings are subject to the following rules:

  • A raw wildcard ("*") may only occur at the end of the match string
  • At least one character must be placed between any two placeholders or wildcards
  • The maximum allowed number of placeholders in a single match string is 64

Match String Examples

  • "/foo/bar" matches only "/foo/bar" itself
  • "/foo/*" matches "/foo/", "/foo/bar", "/foo/bar/baz" or any other string beginning with "/foo/"
  • "/:x/" matches "/foo/", "/bar/" and similar strings (and stores "foo"/"bar" in req.params["x"]), but not "/foo/bar/"
  • Matching partial path entries with wildcards is possible: "/foo:x" matches "/foo", "/foobar", but not "/foo/bar"
  • Multiple placeholders and raw wildcards can be combined: "/:x/:y/*"

Example

import vibe.http.fileserver;

void addGroup(HTTPServerRequest req, HTTPServerResponse res)
{
	// Route variables are accessible via the params map
	logInfo("Getting group %s for user %s.", req.params["groupname"], req.params["username"]);
}

void deleteUser(HTTPServerRequest req, HTTPServerResponse res)
{
	// ...
}

void auth(HTTPServerRequest req, HTTPServerResponse res)
{
	// TODO: check req.session to see if a user is logged in and
	//       write an error page or throw an exception instead.
}

void setup()
{
	auto router = new URLRouter;
	// Matches all GET requests for /users/*/groups/* and places
	// the place holders in req.params as 'username' and 'groupname'.
	router.get("/users/:username/groups/:groupname", &addGroup);

	// Matches all requests. This can be useful for authorization and
	// similar tasks. The auth method will only write a response if the
	// user is _not_ authorized. Otherwise, the router will fall through
	// and continue with the following routes.
	router.any("*", &auth);

	// Matches a POST request
	router.post("/users/:username/delete", &deleteUser);

	// Matches all GET requests in /static/ such as /static/img.png or
	// /static/styles/sty.css
	router.get("/static/*", serveStaticFiles("public/"));

	// Setup a HTTP server...
	auto settings = new HTTPServerSettings;
	// ...

	// The router can be directly passed to the listenHTTP function as
	// the main request handler.
	listenHTTP(settings, router);
}

Example

Using nested routers to map components to different sub paths. A component could for example be an embedded blog engine.

// some embedded component:

void showComponentHome(HTTPServerRequest req, HTTPServerResponse res)
{
	// ...
}

void showComponentUser(HTTPServerRequest req, HTTPServerResponse res)
{
	// ...
}

void registerComponent(URLRouter router)
{
	router.get("/", &showComponentHome);
	router.get("/users/:user", &showComponentUser);
}

// main application:

void showHome(HTTPServerRequest req, HTTPServerResponse res)
{
	// ...
}

void setup()
{
	auto c1router = new URLRouter("/component1");
	registerComponent(c1router);

	auto mainrouter = new URLRouter;
	mainrouter.get("/", &showHome);
	// forward all unprocessed requests to the component router
	mainrouter.any("*", c1router);

	// now the following routes will be matched:
	// / -> showHome
	// /component1/ -> showComponentHome
	// /component1/users/:user -> showComponentUser

	// Start the HTTP server
	auto settings = new HTTPServerSettings;
	// ...
	listenHTTP(settings, mainrouter);
}
Authors

Sönke Ludwig

Copyright

© 2012-2015 Sönke Ludwig

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.