Request

Request

Overview

The Request struct represents the HTTP request. It is passed as the first argument to every server side handler (for both route and API).

use tuono_lib::{Request, Response};

#[tuono_lib::handler]
async fn my_route_handler(req: Request) -> Response {
  // ...
}

The Request argument is required and must always be defined.

Fields

The struct has the following three public fields:

pub struct Request {
  pub uri: Uri,
  pub headers: HeaderMap,
  pub params: HashMap<String, String>,
}

The Request struct contains all the data needed to manage a request. We will soon implement a set of methods to simplify interaction with the request body, cookies, and more.

uri

The uri param represents the current request URI. It is a http crate URI so all its methods are available.

headers

All the headers passed with the request are available in this included Headers, Cookies and Body. It is a http crate HeaderMap so all its methods are available.

params

Within the params HashMap you can find the parameters passed in the dynamic paths.

For example, if we want to read the userId parameter in the following project structure:

├── src
│   └── routes
│       └── [userId]/index.rs

We just have to read the userId key in the params HashMap.

// src/routes/[userId]/index.rs
use tuono_lib::{Request, Response};

#[tuono_lib::handler]
async fn my_route_handler(req: Request) -> Response {
  let user_id = req.params.get("userId").unwrap();
  // ...
}

The same syntax applies also for catch-all dynamic path (i.e. [...userId]).

Methods

body

The body method provides a safe way to read and parse the body of an HTTP request.

Here's an example of using the body method to retrieve data from a POST request.

#[derive(Deserialize)]
struct MyBody {
   pub field: u8
}

#[tuono_lib::api(POST)]
async fn my_post_request(req: Request) -> impl IntoResponse {
    let body: MyBody = req.body().unwrap();
}

Keep in mind that specifying the type is essential, as the method relies on it to determine the appropriate body serialization.

Edit page