Actix Web JsonConfig سے JSON کی خرابیاں حسبِ ضرورت بنائیں
Actix Web کا web::Json<T JSON کو type میں deserialize کرتا ہے اور ناکامی پر handler چلنے سے پہلے رد کرتا ہے۔ web::JsonConfig body کی حد اور custom error handler مقرر کرتا ہے۔ مثال Actix Web 4.19.0 کی ہے۔
Actix Web کا web::Json JSON کو type میں deserialize کرتا ہے اور ناکامی پر handler چلنے سے پہلے رد کرتا ہے۔ web::JsonConfig body کی حد اور custom error handler مقرر کرتا ہے۔ مثال Actix Web 4.19.0 کی ہے۔
Configure the JSON extractor
یہ config route کی body کو 4096 بائٹ تک محدود کرتا ہے۔ error handler JsonPayloadError کا HTTP status برقرار رکھ کر parser کی تفصیل کو مستقل JSON code سے بدلتا ہے۔ درست input واپس آتا ہے، محفوظ نہیں ہوتا۔ بطورِ طے شدہ خراب JSON یا نامناسب Content-Type پر 400، حد سے بڑی body پر 413؛ پڑھنے کی خرابی بنیادی status اپناتی ہے۔
[dependencies]
actix-web = "4.19.0"
serde = { version = "1", features = ["derive"] }Dependencies
use actix_web::{
error,
web::{self, Json},
App, HttpResponse, HttpServer, Responder, ResponseError,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct CreateProject {
name: String,
}
#[derive(Serialize)]
struct ApiError {
code: &'static str,
}
async fn create_project(input: Json<CreateProject>) -> impl Responder {
HttpResponse::Created().json(input.0)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let json_config = web::JsonConfig::default()
.limit(4096)
.error_handler(|err, _req| {
let status = err.status_code();
let response = HttpResponse::build(status).json(ApiError {
code: "invalid_request",
});
error::InternalError::from_response(err, response).into()
});
App::new()
.app_data(json_config)
.route("/projects", web::post().to(create_project))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}src/main.rs
undefined
Verify locally
cargo run چلائیں۔ Content-Type: application/json اور {"name":"Notes"} کے ساتھ http://127.0.0.1:8080/projects پر POST کریں۔ متوقع 201 اور {"name":"Notes"}۔ غلط JSON پر 400، 4096 بائٹ سے بڑی body پر 413؛ دونوں میں {"code":"invalid_request"}۔ compile یا run نہیں کیا گیا۔
Official sources
[Actix Web 4.19.0 source 1](https://actix.rs/docs/extractors)
[Actix Web 4.19.0 source 2](https://docs.rs/actix-web/4.19.0/actix_web/web/struct.JsonConfig.html)
[Actix Web 4.19.0 source 3](https://docs.rs/actix-web/4.19.0/actix_web/error/enum.JsonPayloadError.html)
[Actix Web 4.19.0 source 4](https://actix.rs/docs/errors)