From e80250d00d62761d80b6caf9750dd5b7e80af8ef Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Sun, 14 Sep 2025 11:28:19 +0800 Subject: perf(httpconnector): unified handle_response --- src/client/connector/connectors/httpconnector.rs | 78 +++++++++++------------- 1 file changed, 37 insertions(+), 41 deletions(-) diff --git a/src/client/connector/connectors/httpconnector.rs b/src/client/connector/connectors/httpconnector.rs index a671b94..5c1cc73 100644 --- a/src/client/connector/connectors/httpconnector.rs +++ b/src/client/connector/connectors/httpconnector.rs @@ -1,13 +1,16 @@ -use reqwest::{Error, StatusCode, Url, blocking::Client}; +use reqwest::{ + Error, StatusCode, Url, + blocking::{Client, Response}, +}; -use crate::connector::{self, *}; +use crate::connector::*; use std::{thread::sleep, time::Duration}; pub(crate) struct HTTPConnector { pull_url: Url, ntfy_url: Url, client: Client, - prev: ::Ok, + prev: ::Ok, } impl HTTPConnector { @@ -19,6 +22,30 @@ impl HTTPConnector { client: Client::new(), }) } + + fn handle_response std::result::Result>( + &self, + resp: F, + ) -> Result<::Ok, ::Err> { + match resp() { + Ok(resp) => match resp.status() { + StatusCode::TOO_MANY_REQUESTS => { + sleep(Duration::from_secs(5)); + return self.update(); + } + status => { + if !status.is_success() { + return Result::Err(Err::StatusCode(status)); + } + match resp.text() { + Ok(text) => Result::Ok(text), + Err(e) => return Result::Err(Err::Reqwest(e)), + } + } + }, + Err(e) => return Result::Err(Err::Reqwest(e)), + } + } } pub(crate) enum Err { @@ -40,47 +67,16 @@ impl Connection for HTTPConnector { // consider StatusCode::NOT_MODIFIED fn update(&self) -> Result { - Result::Ok(match self.client.get(self.pull_url.as_str()).send() { - Ok(resp) => match resp.status() { - StatusCode::TOO_MANY_REQUESTS => { - sleep(Duration::from_secs(5)); - return self.update(); - } - status => { - if !status.is_success() { - return Result::Err(Err::StatusCode(status)); - } - match resp.text() { - Ok(text) => text, - Err(e) => return Result::Err(Err::Reqwest(e)), - } - } - }, - Err(e) => return Result::Err(Err::Reqwest(e)), - }) + self.handle_response(|| self.client.get(self.pull_url.as_str()).send()) } fn ntfy(&self, data: String) -> Result { - Result::Ok( - match self.client.post(self.ntfy_url.as_str()).body(data).send() { - Ok(resp) => match resp.status() { - StatusCode::TOO_MANY_REQUESTS => { - sleep(Duration::from_secs(5)); - return self.update(); - } - status => { - if !status.is_success() { - return Result::Err(Err::StatusCode(status)); - } - match resp.text() { - Ok(text) => text, - Err(e) => return Result::Err(Err::Reqwest(e)), - } - } - }, - Err(e) => return Result::Err(Err::Reqwest(e)), - }, - ) + self.handle_response(|| { + self.client + .post(self.ntfy_url.as_str()) + .body(data.to_owned()) + .send() + }) } fn is_prev(&mut self, str: &Self::Ok) -> bool { -- cgit v1.2.3