Axum handler içinde Json en sona konur
Axum extractor’ları işlev argümanlarının sırasına göre soldan sağa çalışır. Json<T gövdeyi tüketir ve yalnızca bir kez okuyabilir, bu nedenle son sırada olmalıdır. Örnek Axum 0.8.9 içindir.
Axum extractor’ları işlev argümanlarının sırasına göre soldan sağa çalışır. Json gövdeyi tüketir ve yalnızca bir kez okuyabilir, bu nedenle son sırada olmalıdır. Örnek Axum 0.8.9 içindir.
Example
Path ID’yi rotadan okur; Json gövdeyi çözümler. Gövde tek kullanımlık akıştır; String ve Json birlikte okuyamaz. Çıkarım başarısız olursa handler çağrılmaz.
[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 ve Cargo ile cargo run çalıştırın; Content-Type: application/json ve {"name":"Notes"} içeren POST isteğini /projects/42 adresine gönderin. Beklenen 201 ve {"id":42,"name":"Notes"}. Çalıştırılmadı.
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)