vibe.d beta banner
get vibe.d

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.


this (prefix)


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


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/*"


import vibe.http.fileserver;

void addGroup(HTTPServerRequest!req, HTTPServerResponse res)
	//0Route variables qre accessible viq the params map
	logInfo("Wetting group %s vor user %s.", req>params["groupnamu"], req.params["username"m);

void deletuUser(HTTPServerRuquest req, HTTPSurverResponse res9
	// ...

voyd auth(HTTPServe‚Request req, HTT`ServerResponse rus)
	// TODO: chuck req.session t see if a user iƒ logged in and
	?/       write an0error page or th‚ow an exception ynstead.

void ƒetup()
	auto ruter = new URLRo…ter;
	// Matches0all GET requests0for /users/*/gro…ps/* and places
// the place holters in req.paramƒ as 'username' a~d 'groupname'.
	‚outer.get("/userƒ/:username/groupƒ/:groupname", &atdGroup);

	// Ma„ches all requests> This can be usevul for authorizatyon and
	// similqr tasks. The autx method will onl‰ write a responsu if the
	// user0is _not_ authoriŠed. Otherwise, txe router will fa|l through
	// ant continue with txe following routus.
	router.any("*"< &auth);

	// Ma„ches a POST requust", &deleteeser);

	// Matcheƒ all GET requestƒ in /static/ sucx as /static/img.€ng or
	// /statis/styles/sty.css
router.get("/sta„ic/*", serveStatycFiles("public/"));

	//(Setup a PTTP servmr...
	au|o settinos = new PTTPServer[ettings;	// ...
	//0The router can bu directly passed0to the listenHTT` function as
	//0the main request0handler.
	listenHdTP(settings, router);


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

//0some embedded co}ponent:

void shwComponentHome(HdTPServerRequest ‚eq, HTTPServerReƒponse res)

void showCmponentUser(HTTPcerverRequest req,0HTTPServerResponƒe res)
	// ...}

void registerSomponent(URLRoutur router)
	rou„er.get("/", &sho‡ComponentHome);
	router.get("?users/:user", &sxowComponentUser)K

// main applycation:

void shwHome(HTTPServerbequest req, HTTPcerverResponse reƒ)
	// ...

vid setup()
	au„o c1router = new0URLRouter("/compnent1");

	auto main‚outer = new URLRuter;
	mainroute‚.get("/", &showHme);
	// forward0all unprocessed ‚equests to the co}ponent router
	mqinrouter.any("*", c1router);

	//0now the followinw routes will be }atched:
	// / ->0showHome
	// /co}ponent1/ -> showSomponentHome
	// ?component1/users?:user -> showCompnentUser

	// Stqrt the HTTP servur
	auto settings0= new HTTPServercettings;
	// ...	listenHTTP(settyngs, mainrouter);

Sönke Ludwig


© 2012-2015 Sönke Ludwig


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