Skip to content

Instantly share code, notes, and snippets.

@hguandl
Created August 31, 2022 05:27
Show Gist options
  • Save hguandl/39dd057c16bc9f69b53f47b04ae530a8 to your computer and use it in GitHub Desktop.
Save hguandl/39dd057c16bc9f69b53f47b04ae530a8 to your computer and use it in GitHub Desktop.
Rust client provider demo
use lazy_static::lazy_static;
use reqwest::Client;
use tokio::sync::{Mutex, MutexGuard};
pub struct ClientProvider {
client: Mutex<Client>,
}
impl ClientProvider {
pub fn new() -> Self {
ClientProvider {
client: Mutex::new(Client::new()),
}
}
pub async fn get(&self) -> MutexGuard<Client> {
self.client.lock().await
}
pub async fn set(&self, client: Client) {
*self.client.lock().await = client;
}
}
impl Default for ClientProvider {
fn default() -> Self {
Self::new()
}
}
lazy_static! {
static ref CLIENT_PROVIDER: ClientProvider = ClientProvider::default();
}
#[tokio::main]
async fn main() {
{
let client = CLIENT_PROVIDER.get().await;
let request = client.get("https://example.com");
request.send().await.unwrap();
}
{
let new_client = Client::new();
CLIENT_PROVIDER.set(new_client).await;
let request = CLIENT_PROVIDER.get().await.get("https://example.com");
request.send().await.unwrap();
}
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment