Middleware для явного указания кодировки в заголовке Content-Type.

This commit is contained in:
2025-04-16 16:21:53 +04:00
parent ff05614404
commit e71ab0526d
3 changed files with 69 additions and 3 deletions

View File

@@ -0,0 +1,64 @@
use actix_web::Error;
use actix_web::body::{BoxBody, EitherBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::http::header;
use actix_web::http::header::HeaderValue;
use futures_util::future::LocalBoxFuture;
use std::future::{Ready, ready};
/// Middleware to specify the encoding in the Content-Type header.
pub struct ContentTypeBootstrap;
impl<S, B> Transform<S, ServiceRequest> for ContentTypeBootstrap
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B, BoxBody>>;
type Error = Error;
type Transform = ContentTypeMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(ContentTypeMiddleware { service }))
}
}
pub struct ContentTypeMiddleware<S> {
service: S,
}
impl<'a, S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<EitherBody<B, BoxBody>>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let fut = self.service.call(req);
Box::pin(async move {
let mut response = fut.await?;
let headers = response.response_mut().headers_mut();
if let Some(content_type) = headers.get("Content-Type") {
if content_type == "application/json" {
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json; charset=utf8"),
);
}
}
Ok(response.map_into_left_body())
})
}
}

View File

@@ -1 +1,2 @@
pub mod authorization;
pub mod authorization;
pub mod content_type;