1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
use std::fmt; use std::sync::Arc; use crate::http::{Method, Url}; use crate::middleware::{Middleware, Next}; use crate::{HttpClient, Request, RequestBuilder, Response, Result}; use futures_util::future::BoxFuture; #[cfg(all( any(feature = "curl-client", feature = "wasm-client"), not(feature = "h1-client") ))] use http_client::native::NativeClient; #[cfg(feature = "h1-client")] use http_client::h1::H1Client; /// An HTTP client, capable of sending `Request`s and running a middleware stack. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::Client::new(); /// let res1 = client.recv_string(surf::get("https://httpbin.org/get")); /// let res2 = client.recv_string(surf::get("https://httpbin.org/get")); /// let (str1, str2) = futures_util::future::try_join(res1, res2).await?; /// # Ok(()) } /// ``` pub struct Client { base_url: Option<Url>, http_client: Arc<dyn HttpClient>, /// Holds the middleware stack. middleware: Arc<Vec<Arc<dyn Middleware>>>, } impl Clone for Client { /// Clones the Client. /// /// This copies the middleware stack from the original, but shares /// the `HttpClient` of the original. /// Note that individual middleware in the middleware stack are /// still shared by reference. fn clone(&self) -> Self { Self { base_url: self.base_url.clone(), http_client: self.http_client.clone(), middleware: Arc::new(self.middleware.iter().cloned().collect()), } } } impl fmt::Debug for Client { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Client {{}}") } } impl Default for Client { fn default() -> Self { Self::new() } } impl Client { /// Create a new instance. /// /// # Examples /// /// ```rust /// let client = surf::Client::new(); /// ``` pub fn new() -> Self { #[cfg(all( any(feature = "curl-client", feature = "wasm-client"), not(feature = "h1-client") ))] let client = NativeClient::new(); #[cfg(feature = "h1-client")] let client = H1Client::new(); Self::with_http_client(Arc::new(client)) } /// Create a new instance with an `http_client::HttpClient` instance. /// /// # Examples /// /// ```rust /// # use std::sync::Arc; /// # use http_client::h1::H1Client; /// let client = surf::Client::with_http_client(Arc::new(H1Client::new())); /// ``` pub fn with_http_client(http_client: Arc<dyn HttpClient>) -> Self { Self { base_url: None, http_client, middleware: Arc::new(vec![ #[cfg(feature = "middleware-logger")] Arc::new(crate::middleware::Logger::new()), ]), } } /// Push middleware onto the middleware stack. /// /// See the [middleware] submodule for more information on middleware. /// /// [middleware]: ../middleware/index.html /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let req = surf::get("https://httpbin.org/get"); /// let client = surf::client() /// .with(surf::middleware::Redirect::default()); /// let res = client.send(req).await?; /// # Ok(()) } /// ``` pub fn with(mut self, middleware: impl Middleware) -> Self { let m = Arc::get_mut(&mut self.middleware) .expect("Registering middleware is not possible after the Client has been used"); m.push(Arc::new(middleware)); self } /// Send a Request using this client. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let req = surf::get("https://httpbin.org/get"); /// let client = surf::client(); /// let res = client.send(req).await?; /// # Ok(()) } /// ``` pub fn send(&self, req: impl Into<Request>) -> BoxFuture<'static, Result<Response>> { let req: Request = req.into(); let http_client = self.http_client.clone(); let middleware = self.middleware.clone(); Box::pin(async move { let next = Next::new(&middleware, &|req, client| { Box::pin(async move { let req: http_types::Request = req.into(); client.http_client.send(req).await.map(Into::into) }) }); let res = next.run(req, Client::with_http_client(http_client)).await?; Ok(Response::new(res.into())) }) } /// Submit the request and get the response body as bytes. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let req = surf::get("https://httpbin.org/get"); /// let bytes = surf::client().recv_bytes(req).await?; /// assert!(bytes.len() > 0); /// # Ok(()) } /// ``` pub async fn recv_bytes(&self, req: impl Into<Request>) -> Result<Vec<u8>> { let mut res = self.send(req.into()).await?; Ok(res.body_bytes().await?) } /// Submit the request and get the response body as a string. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let req = surf::get("https://httpbin.org/get"); /// let string = surf::client().recv_string(req).await?; /// assert!(string.len() > 0); /// # Ok(()) } /// ``` pub async fn recv_string(&self, req: impl Into<Request>) -> Result<String> { let mut res = self.send(req.into()).await?; Ok(res.body_string().await?) } /// Submit the request and decode the response body from json into a struct. /// /// # Examples /// /// ```no_run /// # use serde::{Deserialize, Serialize}; /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// #[derive(Deserialize, Serialize)] /// struct Ip { /// ip: String /// } /// /// let req = surf::get("https://api.ipify.org?format=json"); /// let Ip { ip } = surf::client().recv_json(req).await?; /// assert!(ip.len() > 10); /// # Ok(()) } /// ``` pub async fn recv_json<T: serde::de::DeserializeOwned>( &self, req: impl Into<Request>, ) -> Result<T> { let mut res = self.send(req.into()).await?; Ok(res.body_json::<T>().await?) } /// Submit the request and decode the response body from form encoding into a struct. /// /// # Errors /// /// Any I/O error encountered while reading the body is immediately returned /// as an `Err`. /// /// If the body cannot be interpreted as valid json for the target type `T`, /// an `Err` is returned. /// /// # Examples /// /// ```no_run /// # use serde::{Deserialize, Serialize}; /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// #[derive(Deserialize, Serialize)] /// struct Body { /// apples: u32 /// } /// /// let req = surf::get("https://api.example.com/v1/response"); /// let Body { apples } = surf::client().recv_form(req).await?; /// # Ok(()) } /// ``` pub async fn recv_form<T: serde::de::DeserializeOwned>( &self, req: impl Into<Request>, ) -> Result<T> { let mut res = self.send(req.into()).await?; Ok(res.body_form::<T>().await?) } /// Perform an HTTP `GET` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.get("https://httpbin.org/get").recv_string().await?; /// # Ok(()) } /// ``` pub fn get(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Get, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `HEAD` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.head("https://httpbin.org/head").recv_string().await?; /// # Ok(()) } /// ``` pub fn head(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Head, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `POST` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.post("https://httpbin.org/post").recv_string().await?; /// # Ok(()) } /// ``` pub fn post(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Post, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `PUT` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.put("https://httpbin.org/put").recv_string().await?; /// # Ok(()) } /// ``` pub fn put(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Put, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `DELETE` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.delete("https://httpbin.org/delete").recv_string().await?; /// # Ok(()) } /// ``` pub fn delete(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Delete, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `CONNECT` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.connect("https://httpbin.org/connect").recv_string().await?; /// # Ok(()) } /// ``` pub fn connect(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Connect, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `OPTIONS` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.options("https://httpbin.org/options").recv_string().await?; /// # Ok(()) } /// ``` pub fn options(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Options, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `TRACE` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.trace("https://httpbin.org/trace").recv_string().await?; /// # Ok(()) } /// ``` pub fn trace(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Trace, self.url(uri)).with_client(self.clone()) } /// Perform an HTTP `PATCH` request using the `Client` connection. /// /// # Panics /// /// This will panic if a malformed URL is passed. /// /// # Errors /// /// Returns errors from the middleware, http backend, and network sockets. /// /// # Examples /// /// ```no_run /// # #[async_std::main] /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { /// let client = surf::client(); /// let string = client.patch("https://httpbin.org/patch").recv_string().await?; /// # Ok(()) } /// ``` pub fn patch(&self, uri: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(Method::Patch, self.url(uri)).with_client(self.clone()) } /// Sets the base URL for this client. All request URLs will be relative to this path. /// /// # Examples /// ```no_run /// # use http_types::Url; /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async { /// let mut client = surf::client(); /// client.set_base_url(Url::parse("http://example.com/api/v1")?); /// client.get("/posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json /// # Ok(()) }) } /// ``` pub fn set_base_url(&mut self, base: Url) { self.base_url = Some(base); } // private function to generate a url based on the base_path fn url(&self, uri: impl AsRef<str>) -> Url { match &self.base_url { None => uri.as_ref().parse().unwrap(), Some(base) => base.join(uri.as_ref()).unwrap(), } } }