Ilagay sa huli ang Json sa Axum handler
Tumatakbo ang Axum extractor mula kaliwa pakanan ayon sa ayos ng argumento. Isang beses lang mababasa ng Json<T ang body kaya dapat itong huling argumento. Para ito sa Axum 0.8.9.
Tumatakbo ang Axum extractor mula kaliwa pakanan ayon sa ayos ng argumento. Isang beses lang mababasa ng Json ang body kaya dapat itong huling argumento. Para ito sa Axum 0.8.9.
Example
Binabasa ng Path ang ID sa ruta; dini-deserialize ng Json ang body. Isang beses lang makokonsumo ang body, kaya hindi ito parehong mababasa ng String at Json. Sa extraction failure, hindi tinatawag ang 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
Gamit ang Rust at Cargo, patakbuhin ang cargo run at mag-POST sa /projects/42 na may Content-Type: application/json at {"name":"Notes"}. Inaasahan ang 201 at {"id":42,"name":"Notes"}. Hindi ito pinatakbo.
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)