reqwest_cross/platform/
native.rs

1//! Stores the code specific to native compilations
2// but the comments are for both because these are the ones that show on docs.rs
3
4use crate::{BoundedFuture, DoneHandler};
5
6#[cfg(not(feature = "native-tokio"))]
7compile_error!("Must chose a native runtime by enabling a feature flag. Right now only tokio is supported. If you have a different runtime that you want please create an issue on github.");
8
9/// Performs a HTTP requests and calls the given callback when done with the
10/// result of the request. This is a more flexible API but requires more
11/// boilerplate, see [fetch_plus][crate::fetch_plus] which wraps a lot more of
12/// the boilerplate especially if you need a "wake_up" function.  NB: Needs to
13/// use a callback to prevent blocking on the thread that initiates the fetch.
14/// Note: Instead of calling get like in the example you can use post, put, etc.
15/// (See [reqwest::Client]). Also see the examples
16/// [folder](https://github.com/c-git/reqwest-cross/tree/main/examples)
17/// for more complete examples.
18///
19/// # Example
20/// ```rust
21/// # use reqwest_cross::fetch;
22///
23/// # #[cfg(all(not(target_arch = "wasm32"),feature = "native-tokio"))]
24/// # #[tokio::main(flavor = "current_thread")]
25/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
26///  let client = reqwest::Client::new();
27///  let request = client.get("https://httpbin.org/get");
28///  let (tx, rx) = futures::channel::oneshot::channel();
29///
30///  fetch(request, move |result: Result<reqwest::Response, reqwest::Error>| async {
31///      tx.send(result.expect("Expecting Response not Error").status())
32///                .expect("Receiver should still be available");
33///  });
34///
35///  let status = rx.await?; //In actual use case code to prevent blocking use try_recv instead
36///  assert_eq!(status, 200);
37/// # Ok(())
38/// # }
39///
40/// # #[cfg(target_arch = "wasm32")]
41/// # fn main(){}
42/// ```
43pub fn fetch<F, O>(request: reqwest::RequestBuilder, on_done: F)
44where
45    F: DoneHandler<O>,
46    O: BoundedFuture<()>,
47{
48    let future = async move {
49        let result = request.send().await;
50        on_done(result).await;
51    };
52    spawn(future);
53}
54
55/// Spawns a future on the underlying runtime in a cross platform way (NB: the
56/// Send bound is removed in WASM)
57#[cfg(feature = "native-tokio")]
58pub fn spawn<F>(future: F)
59where
60    F: 'static + Send + futures::Future,
61    F::Output: Send + 'static,
62{
63    tokio::spawn(future);
64}