Skip to content

Routing

Hayley edited this page Sep 13, 2020 · 2 revisions

The Router<R> middleware allows for simple request routing in order to chose which route should respond to a request based on it's uri.

The signature of the Router<R> constructor is as follows

Router(http_method method, vector<string> uris);

Where method is the HTTP method to match for the route and uris is vector of strings specifying the uris to match. Uris is a vector to allow for multiple uris to be responded to by the same route. An example usage of this would be

Outcome middlewares() {
  return MiddleWares<UserDefinedRoute>()
      .add(new Router<UserDefinedRoute>(HTTP_GET_METHOD, {"/", "/home"}))
      .outcome(*this)
}

where a GET request to either / or /home will be responded to by the UserDefinedRoute route

Variable path segments

The router is able to handle path variables to enable dynamic functionality based on the entered path. Path variables are defined by surrounding an identifier with pointy brackets (<>). For an example

/hello/<name>

for the uri /hello/hayley would set the name variable to hayley. All routes which utilize the router must have a public uri_vars attribute as follows

UriVars uri_vars;

which is a hashmap of all the identifiers and their corresponding values so

uri_vars["name"] == "hayley"

Uri arguments

Uri arguments are handled in much the same way as variable path segments. For an example

/hello/<name>?<age>

for the uri /hello/hayley?age=2, uri_vars["name"] would be hayley and uri_vargs["age"] would be 2.

Note: that 2 is stored as string not an integer in the uri_vars hashmap.

Clone this wiki locally