How it works...

In this recipe, we created a Rust project named nickel-routing, which helps us to create multiple endpoints in our web application, and each endpoint displays different custom messages.

Starting at the top, we referenced the external nickel crate using the extern keyword and loading all of its macros with #[macro_use]. We use nickel as the application object and surface, which holds all the public APIs. It's a struct that implements all the fundamental methods for performing all the web application tasks, and HttpRouter is a public trait provided by the nickle crate, which has the signature of various REST API calls.

In the main function, we first assign server instances to a mutable variable and create a new nickel application object with Nickel::new(), which creates an instance of nickel with default error handling.

The server.get method registers a handler to be used for a specific get request. Handlers are assigned to paths and paths are allowed to contain variables and wildcards. A handler added through this API will be attached to the default router. The middleware! macro reduces the amount of boilerplate code needed for each route.

We create the following routes in this recipe:

  • /bar: On hitting this endpoint, we get the message, This is the /bar handler.
  • /user/:userid: On hitting this endpoint, we get the message, This is user: {:?}. Here, the argument is replaced with the data (:userid) passed in the get request with the request.param("userid") command, where param is a method of the request struct.
  • /a/*/d: On hitting this endpoint, we get the message, matches /a/b/d but not /a/b/c/d. The asterisk here allows only one intermediate path.
  • /a/**/d: On hitting this endpoint, we get a message: This matches /a/b/d and also /a/b/c/d. The asterisk here allows only two intermediate paths.
Routes can be as simple as /foo, use parameters, wildcards, and even double wildcards.

The server.listen method listens to the API requests on 127.0.0.1:6767 where it binds and listens for connections on the given host and port.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.8