GET – Reading data

When data is created, we need to be able to read it. For this case, we can use the HTTP GET method. Add the following branch to the code:

(&Method::GET, Some(id)) => {
if let Some(data) = users.get(id) {
Response::new(data.to_string().into())
} else {
response_with_code(StatusCode::NOT_FOUND)
}
}

This code uses the user database to try to find the user by the ID that's provided in the path. If the user is found, we'll convert its data to a String and into a Body to send with a Response.

If the user isn't found, the handler branch will respond with the NOT_FOUND status code (the classic 404 error).

To make the UserData convertible to a String, we have to implement the ToString trait for that type. However, it's typically more useful to implement the Display trait, because ToString will be derived automatically for every type that implements the Display trait. Add this code somewhere in the main.rs source file:

impl fmt::Display for UserData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("{}")
}
}

In this implementation, we return a string with an empty JSON object "{}". Real microservices have to use the serde trait for such conversions.

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

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