Axum हैंडलर में Json को आख़िर में रखें
Axum extractors फ़ंक्शन तर्कों के क्रम में चलते हैं। Json<T अनुरोध बॉडी को केवल एक बार पढ़ सकता है, इसलिए उसे आख़िरी तर्क होना चाहिए। यह उदाहरण Axum 0.8.9 के लिए है।
Axum extractors फ़ंक्शन तर्कों के क्रम में चलते हैं। Json अनुरोध बॉडी को केवल एक बार पढ़ सकता है, इसलिए उसे आख़िरी तर्क होना चाहिए। यह उदाहरण Axum 0.8.9 के लिए है।
Example
Path रूट से ID पढ़ता है और Json बॉडी deserialize करता है। बॉडी एक बार उपयोग होने वाली stream है; String और Json दोनों इसे नहीं पढ़ सकते। extraction विफल हो तो handler नहीं बुलाया जाता।
[dependencies]
axum = "0.8.9"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }Dependencies
use axum::{
extract::Path,
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateProject {
name: String,
}
#[derive(Serialize)]
struct ProjectReply {
id: u64,
name: String,
}
async fn create_project(
Path(project_id): Path<u64>,
Json(input): Json<CreateProject>,
) -> (StatusCode, Json<ProjectReply>) {
(
StatusCode::CREATED,
Json(ProjectReply {
id: project_id,
name: input.name,
}),
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/projects/{id}", post(create_project));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.expect("bind listener");
axum::serve(listener, app).await.expect("serve app");
}src/main.rs
undefined
Rust और Cargo के साथ cargo run चलाएँ और /projects/42 पर Content-Type: application/json तथा {"name":"Notes"} के साथ POST भेजें। अपेक्षित 201 और {"id":42,"name":"Notes"}। चलाया नहीं गया।
Local verification
undefined
Official sources
[Axum 0.8.9](https://docs.rs/axum/0.8.9/axum/extract/)
[Axum 0.8.9](https://docs.rs/axum/0.8.9/axum/error_handling/)
[Axum 0.8.9](https://docs.rs/axum/0.8.9/axum/struct.Router.html)
[IntoResponse reference](https://docs.rs/axum/0.8.9/axum/response/trait.IntoResponse.html)