From 7554d4c87c026313a1f5b3c7ae66a92b5ff7e091 Mon Sep 17 00:00:00 2001 From: Elizabeth Engelman <4752801+elizabethengelman@users.noreply.github.com> Date: Sun, 13 Oct 2024 22:39:09 -0400 Subject: [PATCH] Feat/new client with headers (#13) --- src/lib.rs | 50 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index eed04a1..821a68d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -659,14 +659,7 @@ impl Client { let uri = Uri::from_parts(parts).map_err(Error::InvalidRpcUrlFromUriParts)?; let base_url = Arc::from(uri.to_string()); tracing::trace!(?uri); - let mut headers = HeaderMap::new(); - headers.insert("X-Client-Name", unsafe { - "soroban-cli".parse().unwrap_unchecked() - }); - let version = VERSION.unwrap_or("devel"); - headers.insert("X-Client-Version", unsafe { - version.parse().unwrap_unchecked() - }); + let headers = Self::default_http_headers(); let http_client = Arc::new( HttpClientBuilder::default() .set_headers(headers) @@ -679,11 +672,6 @@ impl Client { }) } - #[must_use] - pub fn base_url(&self) -> &str { - &self.base_url - } - /// Create a new client with a timeout in seconds /// # Errors pub fn new_with_timeout(base_url: &str, timeout: u64) -> Result { @@ -692,6 +680,42 @@ impl Client { Ok(client) } + /// Create a new client with additional headers + /// # Errors + pub fn new_with_headers(base_url: &str, additional_headers: HeaderMap) -> Result { + let mut client = Self::new(base_url)?; + let mut headers = Self::default_http_headers(); + + for (key, value) in additional_headers { + headers.insert(key.ok_or(Error::InvalidResponse)?, value); + } + let http_client = Arc::new( + HttpClientBuilder::default() + .set_headers(headers) + .build(base_url)?, + ); + + client.http_client = http_client; + Ok(client) + } + + fn default_http_headers() -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert("X-Client-Name", unsafe { + "rs-stellar-rpc-client".parse().unwrap_unchecked() + }); + let version = VERSION.unwrap_or("devel"); + headers.insert("X-Client-Version", unsafe { + version.parse().unwrap_unchecked() + }); + headers + } + + #[must_use] + pub fn base_url(&self) -> &str { + &self.base_url + } + #[must_use] pub fn client(&self) -> &HttpClient { &self.http_client