Created
October 13, 2018 21:44
-
-
Save epequeno/812ba2f91726a6b79e366b89894ffd64 to your computer and use it in GitHub Desktop.
example of re-creating a client when an initial request gets a 401 response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate reqwest; | |
use reqwest::*; | |
#[derive(Debug)] | |
struct MyClient { | |
client: Client, | |
token: String | |
} | |
impl MyClient { | |
fn new() -> MyClient { | |
MyClient { | |
client: Client::new(), | |
token: "".to_string() | |
} | |
} | |
pub fn get(&mut self, url: &str) -> Result<Response> { | |
let url_clone = url.clone(); | |
let u = Url::parse(&url_clone).unwrap(); | |
let init_res = self.client.get(u).send().unwrap(); | |
if init_res.status() == StatusCode::UNAUTHORIZED { | |
println!("generating new client"); | |
self.client = Client::new(); | |
let u = Url::parse(&url_clone).unwrap(); | |
return Ok(self.client.get(u).send()?) | |
} | |
Ok(init_res) | |
} | |
} | |
fn main() { | |
let mut my_client = MyClient::new(); | |
let url = "https://httpstat.us/401"; | |
let res = my_client.get(url).unwrap(); | |
println!("{:#?}", res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment