Đặt Json ở cuối handler Axum
Extractor Axum chạy từ trái sang phải theo thứ tự tham số. Json<T tiêu thụ phần thân một lần nên phải là tham số cuối. Ví dụ áp dụng Axum 0.8.9.
Extractor Axum chạy từ trái sang phải theo thứ tự tham số. Json tiêu thụ phần thân một lần nên phải là tham số cuối. Ví dụ áp dụng Axum 0.8.9.
Example
Path đọc ID từ route; Json giải tuần tự hóa phần thân. Đây là luồng chỉ dùng một lần nên String và Json không thể cùng đọc. Khi trích xuất lỗi, handler không được gọi.
[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
Cài Rust và Cargo, chạy cargo run rồi gửi POST đến /projects/42 với Content-Type: application/json và {"name":"Notes"}. Mong đợi 201 và {"id":42,"name":"Notes"}. Chưa chạy.
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)