在 Axum 處理函式中將 Json 放最後
Axum extractor 依引數順序由左至右執行。Json<T 會消耗主體且只能讀取一次,因此必須放最後。範例適用於 Axum 0.8.9。
發布 更新
Axum extractor 依引數順序由左至右執行。Json 會消耗主體且只能讀取一次,因此必須放最後。範例適用於 Axum 0.8.9。
Example
Path 從路由讀取 ID,Json 反序列化主體。主體只能消耗一次,因此 String 和 Json 無法同時讀取。擷取失敗時不會呼叫處理函式。
[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)