1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-30 12:00:38 +00:00

Impl BodyEncoding for Response (#740)

This commit is contained in:
Douman 2019-03-30 02:29:11 +03:00 committed by Nikolay Kim
parent c126713f40
commit 00526f60dc
3 changed files with 44 additions and 1 deletions

View file

@ -189,6 +189,18 @@ impl<B> Response<B> {
self.head.keep_alive()
}
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<Extensions> {
self.head.extensions.borrow()
}
/// Mutable reference to a the response's extensions
#[inline]
pub fn extensions_mut(&mut self) -> RefMut<Extensions> {
self.head.extensions.borrow_mut()
}
/// Get body os this response
#[inline]
pub fn body(&self) -> &ResponseBody<B> {

View file

@ -6,7 +6,7 @@ use std::str::FromStr;
use actix_http::body::MessageBody;
use actix_http::encoding::Encoder;
use actix_http::http::header::{ContentEncoding, ACCEPT_ENCODING};
use actix_http::ResponseBuilder;
use actix_http::{Response, ResponseBuilder};
use actix_service::{Service, Transform};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
@ -27,6 +27,13 @@ impl BodyEncoding for ResponseBuilder {
}
}
impl<B> BodyEncoding for Response<B> {
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
self.extensions_mut().insert(Enc(encoding));
self
}
}
#[derive(Debug, Clone)]
/// `Middleware` for compressing response body.
///

View file

@ -96,10 +96,20 @@ fn test_body_encoding_override() {
.service(web::resource("/").route(web::to(|| {
use actix_web::middleware::encoding::BodyEncoding;
Response::Ok().encoding(ContentEncoding::Deflate).body(STR)
})))
.service(web::resource("/raw").route(web::to(|| {
use actix_web::middleware::encoding::BodyEncoding;
let body = actix_web::dev::Body::Bytes(STR.into());
let mut response = Response::with_body(actix_web::http::StatusCode::OK, body);
response.encoding(ContentEncoding::Deflate);
response
}))),
)
});
// Builder
let mut response = srv.block_on(srv.get().no_decompress().send()).unwrap();
assert!(response.status().is_success());
@ -111,6 +121,20 @@ fn test_body_encoding_override() {
e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
// Raw Response
let mut response = srv.block_on(srv.request(actix_web::http::Method::GET, srv.url("/raw")).no_decompress().send()).unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.block_on(HttpMessageBody::new(&mut response)).unwrap();
// decode
let mut e = ZlibDecoder::new(Vec::new());
e.write_all(bytes.as_ref()).unwrap();
let dec = e.finish().unwrap();
assert_eq!(Bytes::from(dec), Bytes::from_static(STR.as_ref()));
}
#[cfg(any(feature = "flate2-zlib", feature = "flate2-rust"))]