Skip to main content

ntex/client/
mod.rs

1//! HTTP client.
2//!
3//! ```rust,no_run
4//! use ntex::client::Client;
5//!
6//! #[ntex::main]
7//! async fn main() {
8//!     let client = Client::new();
9//!
10//!     let response = client
11//!         .get("https://www.rust-lang.org")
12//!         .header("User-Agent", "ntex")
13//!         .send()
14//!         .await;
15//!
16//!     println!("Response: {response:?}");
17//! }
18//! ```
19use std::rc::Rc;
20
21mod builder;
22mod cfg;
23mod codec;
24mod connection;
25mod connector;
26pub mod error;
27mod h1proto;
28mod h2proto;
29mod pool;
30mod request;
31mod response;
32mod sender;
33mod service;
34mod test;
35
36pub use self::builder::ClientBuilder;
37pub use self::cfg::ClientConfig;
38pub use self::request::ClientRequest;
39pub use self::response::{ClientResponse, JsonBody, MessageBody};
40pub use self::service::{ServiceRequest, ServiceResponse};
41pub use self::test::TestResponse;
42
43pub(crate) use self::codec::{ClientCodec, ClientPayloadCodec};
44#[cfg(feature = "ws")]
45pub(crate) use self::h1proto::host_header;
46use urly::Url;
47
48use crate::client::error::{ConnectError, InvalidUrl};
49use crate::http::{HeaderMap, Method, RequestHead, body::BodySize};
50use crate::service::{cfg::SharedCfg, pipeline::PipelineState};
51use crate::{Cfg, Pipeline, error::Error, io::IoBoxed};
52
53type ConnectorPipeline = PipelineState<SharedCfg, Connect, IoBoxed, Error<ConnectError>>;
54
55#[derive(Debug, Clone)]
56pub(crate) struct Connect {
57    pub(crate) uri: Url,
58    pub(crate) addr: Option<std::net::SocketAddr>,
59}
60
61/// An HTTP client.
62///
63/// ```rust,no_run
64/// use ntex::client::Client;
65///
66/// #[ntex::main]
67/// async fn main() {
68///     let client = Client::new();
69///
70///     let response = client
71///         .get("https://www.rust-lang.org")
72///         .header("User-Agent", "ntex")
73///         .send()
74///         .await;
75///
76///     println!("Response: {response:?}");
77/// }
78/// ```
79///
80/// # Shutdown
81///
82/// Clones of a client share its connection pools. A pool is stopped once the
83/// last clone and every request created from it are dropped, and dropping does
84/// not wait for connections to close:
85///
86/// - Requests waiting for a connection fail with
87///   [`ConnectError::Disconnected`].
88/// - Idle HTTP/1 connections are shut down in the background, bounded by the
89///   I/O [shutdown timeout](crate::io::IoConfig::set_shutdown_timeout).
90/// - HTTP/2 connections stop accepting requests and are closed gracefully in
91///   the background once their in-flight requests have completed. Their
92///   closing is not bounded by a timeout.
93/// - Responses that are still being read keep their connections. An HTTP/1
94///   connection is closed instead of being returned to the stopped pool.
95/// - A connection that is still being established is closed once the
96///   connect completes.
97#[derive(Debug, Clone)]
98pub struct Client {
99    cfg: Cfg<ClientConfig>,
100    svc: Rc<Pipeline<ServiceRequest, ServiceResponse, Error<error::ClientError>>>,
101}
102
103impl Default for Client {
104    fn default() -> Self {
105        Client::new()
106    }
107}
108
109impl Client {
110    /// Creates a client with default settings.
111    ///
112    /// HTTPS peers are verified by default; see the TLS defaults of
113    /// [`ClientBuilder::new`].
114    pub fn new() -> Client {
115        ClientBuilder::new().build(SharedCfg::default())
116    }
117
118    /// Creates a client builder.
119    pub fn builder() -> ClientBuilder {
120        ClientBuilder::new()
121    }
122
123    /// Creates a client with shared service configuration.
124    pub fn with_config(cfg: impl Into<SharedCfg>) -> Client {
125        ClientBuilder::new().build(cfg.into())
126    }
127
128    pub(crate) fn with_service(
129        cfg: Cfg<ClientConfig>,
130        svc: Pipeline<ServiceRequest, ServiceResponse, Error<error::ClientError>>,
131    ) -> Self {
132        Client {
133            cfg,
134            svc: Rc::new(svc),
135        }
136    }
137
138    /// Waits until the client is ready to process requests.
139    pub async fn ready(&self) -> Result<(), Error<error::ClientError>> {
140        self.svc.ready().await
141    }
142
143    /// Creates an HTTP request with the specified method and URL.
144    pub fn request<U>(&self, method: Method, url: U) -> ClientRequest
145    where
146        Url: TryFrom<U>,
147        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
148    {
149        let mut req = ClientRequest::new(method, url, self.cfg.clone(), self.svc.bind());
150        // the request has no headers yet, every value of a multi-value default is copied
151        for (key, value) in self.cfg.headers() {
152            req.headers_mut().append(key.clone(), value.clone());
153        }
154        req
155    }
156
157    /// Creates a [`ClientRequest`] from a [`RequestHead`].
158    ///
159    /// This is useful for proxy requests. The method and headers are copied
160    /// from `head`; existing client default headers are not overwritten.
161    pub fn request_from<U>(&self, url: U, head: &RequestHead) -> ClientRequest
162    where
163        Url: TryFrom<U>,
164        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
165    {
166        let mut req = self.request(head.method.clone(), url);
167        for (key, value) in &head.headers {
168            // every value of a multi-value header is copied
169            if !self.cfg.headers().contains_key(key) {
170                req.headers_mut().append(key.clone(), value.clone());
171            }
172        }
173        req
174    }
175
176    /// Construct HTTP *GET* request.
177    pub fn get<U>(&self, url: U) -> ClientRequest
178    where
179        Url: TryFrom<U>,
180        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
181    {
182        self.request(Method::GET, url)
183    }
184
185    /// Construct HTTP *HEAD* request.
186    pub fn head<U>(&self, url: U) -> ClientRequest
187    where
188        Url: TryFrom<U>,
189        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
190    {
191        self.request(Method::HEAD, url)
192    }
193
194    /// Construct HTTP *PUT* request.
195    pub fn put<U>(&self, url: U) -> ClientRequest
196    where
197        Url: TryFrom<U>,
198        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
199    {
200        self.request(Method::PUT, url)
201    }
202
203    /// Construct HTTP *POST* request.
204    pub fn post<U>(&self, url: U) -> ClientRequest
205    where
206        Url: TryFrom<U>,
207        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
208    {
209        self.request(Method::POST, url)
210    }
211
212    /// Construct HTTP *PATCH* request.
213    pub fn patch<U>(&self, url: U) -> ClientRequest
214    where
215        Url: TryFrom<U>,
216        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
217    {
218        self.request(Method::PATCH, url)
219    }
220
221    /// Construct HTTP *DELETE* request.
222    pub fn delete<U>(&self, url: U) -> ClientRequest
223    where
224        Url: TryFrom<U>,
225        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
226    {
227        self.request(Method::DELETE, url)
228    }
229
230    /// Construct HTTP *QUERY* request.
231    pub fn query<U>(&self, url: U) -> ClientRequest
232    where
233        Url: TryFrom<U>,
234        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
235    {
236        self.request(Method::QUERY, url)
237    }
238
239    /// Construct HTTP *OPTIONS* request.
240    pub fn options<U>(&self, url: U) -> ClientRequest
241    where
242        Url: TryFrom<U>,
243        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
244    {
245        self.request(Method::OPTIONS, url)
246    }
247}
248
249#[derive(Debug)]
250pub(crate) struct ClientRawRequest {
251    pub(crate) head: crate::http::Message<RequestHead>,
252    pub(crate) headers: Option<HeaderMap>,
253    pub(crate) size: BodySize,
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::http::header::{self, HeaderValue};
260
261    /// STATEMENT: Requests copied from a head retain its method and repeated headers without replacing client defaults.
262    ///
263    /// HOW:
264    /// - Copy a PATCH head with repeated accept values and a conflicting default header.
265    /// - Check method, repeated values, default precedence, and copying when no client default exists.
266    #[crate::rt_test]
267    async fn request_from_head() {
268        let client = Client::builder().build(
269            SharedCfg::new("TEST").add(ClientConfig::new().set_header("x-default", "cfg").unwrap()),
270        );
271        let mut head = RequestHead {
272            method: Method::PATCH,
273            ..Default::default()
274        };
275        head.headers
276            .insert(header::ACCEPT, HeaderValue::from_static("text/html"));
277        head.headers
278            .append(header::ACCEPT, HeaderValue::from_static("text/plain"));
279        head.headers.insert(
280            "x-default".try_into().unwrap(),
281            HeaderValue::from_static("head"),
282        );
283
284        let req = client.request_from("http://localhost/", &head);
285        assert_eq!(req.get_method(), Method::PATCH);
286        let accept: Vec<_> = req.headers().get_all(header::ACCEPT).collect();
287        assert_eq!(accept, ["text/html", "text/plain"]);
288        // client default headers are not overwritten
289        let default: Vec<_> = req.headers().get_all("x-default").collect();
290        assert_eq!(default, ["cfg"]);
291
292        let req = Client::default().request_from("http://localhost/", &head);
293        assert_eq!(req.headers().get("x-default").unwrap(), "head");
294    }
295}