A reqwest::Client is an HTTP client handle for sending requests. It can perform GET, POST, DELETE, and other HTTP actions, while RequestBuilder methods configure details such as timeouts, bodies, and headers. section 17.7.1 section 19.1
Create a default client with Client::default(), then provide a URL to get(). The resulting request must be sent with send(). The default client is asynchronous, so send() produces a Future rather than an immediately available response. section 19.1
Sending a GET request
use reqwest; use tokio; #[tokio::main] async fn main() { let client = reqwest::Client::default(); let response = client .get("https://www.rust-lang.org") .send() .await .unwrap(); println!("{}", response.text().await.unwrap()); } The .await keyword waits for each asynchronous operation. Real applications should handle errors, commonly with the ? operator, instead of relying on unwrap(). section 19.3.3
If only a few requests are needed without async code, reqwest::blocking::Client may be more convenient. That API must be available through the crate’s configuration; otherwise the compiler reports that reqwest::blocking cannot be found. section 19.1
use lazy_static::lazy_static;
use reqwest::Client;
use std::sync::Mutex;
#[derive(Debug)]
struct Logger {
logs: Mutex<Vec<Log>>,
url: String,
client: Client,
}
#[derive(Debug)]
struct Log {
message: String,
timestamp: i64,
}
lazy_static! {
static ref GLOBAL_LOGGER: Logger = Logger {
logs: Mutex::new(vec![]),
url: "https://somethingsomething.com".to_string(),
client: Client::default()
};
}
fn main() {
GLOBAL_LOGGER.logs.lock().unwrap().push(Log {
message: "Everything's going well".to_string(),
timestamp: 1658930674
});
println!("{:#?}", *GLOBAL_LOGGER.logs.lock().unwrap());
}
Shows a Client stored in a global Logger and initialized through lazy_static when ordinary static initialization rejects non-const Client::default(). section 17.7.1
