Skip to main content

ntex/client/
service.rs

1use std::{error::Error, net, rc::Rc};
2
3use serde::Serialize;
4
5use crate::http::body::{Body, BodyStream};
6use crate::http::header::{self, HeaderMap, HeaderName, HeaderValue};
7use crate::http::{Message, Payload, RequestHead, ResponseHead, error::HttpError};
8use crate::{Cfg, time::Millis, util::Bytes, util::Stream};
9
10use super::{ClientConfig, error::ClientError};
11
12#[derive(Debug)]
13/// HTTP response passed through client middleware.
14pub struct ServiceResponse {
15    pub(super) head: ResponseHead,
16    pub(super) payload: Payload,
17    pub(super) config: Cfg<ClientConfig>,
18}
19
20impl ServiceResponse {
21    /// Returns mutable access to the response head.
22    pub fn head(&mut self) -> &mut ResponseHead {
23        &mut self.head
24    }
25
26    /// Returns mutable access to the response payload.
27    pub fn payload(&mut self) -> &mut Payload {
28        &mut self.payload
29    }
30
31    /// Takes the response payload, leaving an empty payload behind.
32    pub fn take_payload(&mut self) -> Payload {
33        std::mem::replace(&mut self.payload, Payload::None)
34    }
35}
36
37#[derive(Debug)]
38/// HTTP request passed through client middleware before it is sent.
39pub struct ServiceRequest {
40    pub(super) head: Message<RequestHead>,
41    pub(super) headers: Option<HeaderMap>,
42    pub(super) addr: Option<net::SocketAddr>,
43    pub(super) body: Body,
44    pub(super) timeout: Option<Millis>,
45    pub(super) response_decompress: bool,
46}
47
48impl ServiceRequest {
49    pub(super) fn new() -> Self {
50        Self {
51            head: Message::new(),
52            headers: None,
53            addr: None,
54            body: Body::None,
55            timeout: None,
56            response_decompress: true,
57        }
58    }
59
60    #[inline]
61    /// Returns mutable access to the request head.
62    pub fn head(&mut self) -> &mut RequestHead {
63        &mut self.head
64    }
65
66    /// Returns mutable access to the request's extra headers.
67    ///
68    /// Extra headers override headers with the same name in the request head
69    /// when the request is encoded.
70    pub fn headers(&mut self) -> &mut HeaderMap {
71        if self.headers.is_none() {
72            self.headers = Some(HeaderMap::new());
73        }
74        self.headers.as_mut().unwrap()
75    }
76
77    /// Returns mutable access to the request body.
78    pub fn body(&mut self) -> &mut Body {
79        &mut self.body
80    }
81
82    /// Returns mutable access to the pre-resolved server address.
83    pub fn address(&mut self) -> &mut Option<net::SocketAddr> {
84        &mut self.addr
85    }
86
87    pub(super) fn set_json<T: Serialize>(&mut self, value: &T) -> Result<(), ClientError> {
88        self.body = crate::http::helpers::json_body(value)
89            .map_err(|e| ClientError::Error(Rc::new(e)))?
90            .into();
91        self.set_header_if_none(header::CONTENT_TYPE, "application/json")?;
92        Ok(())
93    }
94
95    pub(super) fn set_form<T: Serialize>(&mut self, value: &T) -> Result<(), ClientError> {
96        self.body = serde_urlencoded::to_string(value)
97            .map_err(|e| ClientError::Error(Rc::new(e)))?
98            .into();
99        self.set_header_if_none(header::CONTENT_TYPE, "application/x-www-form-urlencoded")?;
100        Ok(())
101    }
102
103    pub(super) fn set_stream<S, E>(&mut self, stream: S)
104    where
105        S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
106        E: Error + 'static,
107    {
108        self.body = BodyStream::new(stream).into();
109    }
110
111    fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError>
112    where
113        HeaderValue: TryFrom<V>,
114        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
115    {
116        if !self.head.headers.contains_key(&key) {
117            self.head
118                .headers
119                .insert(key, HeaderValue::try_from(value).map_err(Into::into)?);
120        }
121
122        Ok(())
123    }
124}