POST – Creating data

When the server has just started, it doesn't contain any data. To support data creation, we use the POST method without the user's ID. Add the following branch to the match (method, user_id) expression:

(&Method::POST, None) => {
let id = users.insert(UserData);
Response::new(id.to_string().into())
}

This code adds a UserData instance to the user database and sends the associated ID of the user in a response with the OK status (an HTTP status code of 200). This code was set by the Response::new function by default.

UserData is an empty struct in this case. In real applications, however, it would have to contain real data. We use an empty struct to avoid serialization, but you can read more about serialization and deserialization based on the serde crate in Chapter 4, Data Serialization and Deserialization with the Serde Crate.

What if the client sets the ID with a POST request? You can interpret this case in two ways—ignore it or try to use the provided ID. In our example, we'll inform the client that the request was wrong. Add the following branch to handle this case:

(&Method::POST, Some(_)) => {
response_with_code(StatusCode::BAD_REQUEST)
}

This code returns a response with the BAD_REQUEST status code (a 400 HTTP status code).

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

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