1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 16:32:43 +01:00
actix-extras/src/client/response.rs

111 lines
2.5 KiB
Rust
Raw Normal View History

2018-11-17 04:28:07 +01:00
use std::cell::RefCell;
use std::fmt;
2018-11-14 07:53:30 +01:00
use bytes::Bytes;
use futures::{Async, Poll, Stream};
2018-11-16 07:34:29 +01:00
use http::{HeaderMap, StatusCode, Version};
use body::PayloadStream;
use error::PayloadError;
use httpmessage::HttpMessage;
2018-11-17 04:28:07 +01:00
use message::{MessageFlags, ResponseHead};
use super::pipeline::Payload;
/// Client Response
pub struct ClientResponse {
2018-11-17 04:28:07 +01:00
pub(crate) head: ResponseHead,
pub(crate) payload: RefCell<Option<PayloadStream>>,
}
impl HttpMessage for ClientResponse {
type Stream = PayloadStream;
fn headers(&self) -> &HeaderMap {
2018-11-17 04:28:07 +01:00
&self.head.headers
}
#[inline]
fn payload(&self) -> Self::Stream {
if let Some(payload) = self.payload.borrow_mut().take() {
payload
} else {
Payload::empty()
}
}
}
impl ClientResponse {
/// Create new Request instance
pub fn new() -> ClientResponse {
ClientResponse {
2018-11-17 04:28:07 +01:00
head: ResponseHead::default(),
payload: RefCell::new(None),
}
}
#[inline]
2018-11-17 04:28:07 +01:00
pub(crate) fn head(&self) -> &ResponseHead {
&self.head
}
#[inline]
2018-11-17 04:28:07 +01:00
pub(crate) fn head_mut(&mut self) -> &mut ResponseHead {
&mut self.head
}
/// Read the Request Version.
#[inline]
pub fn version(&self) -> Version {
2018-11-17 04:28:07 +01:00
self.head().version.clone().unwrap()
}
/// Get the status from the server.
#[inline]
pub fn status(&self) -> StatusCode {
2018-11-17 04:28:07 +01:00
self.head().status
}
#[inline]
/// Returns Request's headers.
pub fn headers(&self) -> &HeaderMap {
2018-11-17 04:28:07 +01:00
&self.head().headers
}
#[inline]
/// Returns mutable Request's headers.
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2018-11-17 04:28:07 +01:00
&mut self.head_mut().headers
}
/// Checks if a connection should be kept alive.
#[inline]
pub fn keep_alive(&self) -> bool {
2018-11-17 04:28:07 +01:00
self.head().flags.contains(MessageFlags::KEEPALIVE)
}
}
2018-11-14 07:53:30 +01:00
impl Stream for ClientResponse {
type Item = Bytes;
type Error = PayloadError;
2018-11-14 07:53:30 +01:00
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if let Some(ref mut payload) = &mut *self.payload.borrow_mut() {
2018-11-14 07:53:30 +01:00
payload.poll()
} else {
Ok(Async::Ready(None))
}
}
}
impl fmt::Debug for ClientResponse {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?;
writeln!(f, " headers:")?;
for (key, val) in self.headers().iter() {
writeln!(f, " {:?}: {:?}", key, val)?;
}
Ok(())
}
}