From 6776ea7b5af4c544da2e34e69cbaaa756d41c862 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 3 May 2020 13:12:30 +0800 Subject: [PATCH] update reqwest --- reqwest/Cargo.lock | 12 ++++++++++++ reqwest/Cargo.toml | 1 + reqwest/src/main.rs | 39 +++++++++++++++++++++++++++++---------- 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/reqwest/Cargo.lock b/reqwest/Cargo.lock index fc7acf3..16c0278 100644 --- a/reqwest/Cargo.lock +++ b/reqwest/Cargo.lock @@ -6,6 +6,17 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b585a98a234c46fc563103e9278c9391fde1f4e6850334da895d27edb9580f62" +[[package]] +name = "async-trait" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da71fef07bc806586090247e971229289f64c210a278ee5ae419314eb386b31d" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "autocfg" version = "1.0.0" @@ -624,6 +635,7 @@ dependencies = [ name = "reqwest" version = "0.1.0" dependencies = [ + "async-trait", "reqwest 0.10.4", "tokio", ] diff --git a/reqwest/Cargo.toml b/reqwest/Cargo.toml index 1e29b10..eaf7a98 100644 --- a/reqwest/Cargo.toml +++ b/reqwest/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +async-trait = "0.1.30" tokio = { version = "0.2.6", features = ["full"] } reqwest = "0.10.4" diff --git a/reqwest/src/main.rs b/reqwest/src/main.rs index b2a2e69..20fe90d 100644 --- a/reqwest/src/main.rs +++ b/reqwest/src/main.rs @@ -9,24 +9,43 @@ pub async fn main() { return; }, }; - let mut map = HashMap::new(); - map.insert("1", test001); + let mut map: HashMap<_, Box> = HashMap::new(); + map.insert("1", Box::new(T001{}) ); + map.insert("2", Box::new(T002{}) ); - let f = match map.get(a.as_str()) { - Some(f) => f, None => { - println!("{}", &format!("[ERROR] Cannot find {}", a)); + let c = match map.get(a.as_str()) { + Some(c) => c, None => { + println!("[ERROR] Cannot find {}", a); return; }, }; - match f().await { + match c.call().await { Ok(_) => println!("[OK] Call fn ok: {}", a), Err(err) => println!("[ERROR] Call fn error: {}, message: {}", a, err), } } -async fn test001() -> Result<(), Box> { - let ip = reqwest::get("https://hatter.ink/ip/ip.jsonp").await?.text().await?; - println!("{}", ip); - Ok(()) +#[async_trait::async_trait] +trait Call { + async fn call(&self) -> Result<(), Box>; +} + +struct T001(); +#[async_trait::async_trait] +impl Call for T001 { + async fn call(&self) -> Result<(), Box> { + let ip = reqwest::get("https://hatter.ink/ip/ip.jsonp").await?.text().await?; + println!("{}", ip); + Ok(()) + } +} + +struct T002(); +#[async_trait::async_trait] +impl Call for T002 { + async fn call(&self) -> Result<(), Box> { + println!("Hello World 2"); + Ok(()) + } }