Skip to content

Commit f33d352

Browse files
committed
feat(jsonrpc): custom request headers
1 parent a6ff645 commit f33d352

File tree

1 file changed

+27
-5
lines changed
  • starknet-providers/src/jsonrpc/transports

1 file changed

+27
-5
lines changed

starknet-providers/src/jsonrpc/transports/http.rs

+27-5
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::jsonrpc::{transports::JsonRpcTransport, JsonRpcMethod, JsonRpcRespons
99
pub struct HttpTransport {
1010
client: Client,
1111
url: Url,
12+
headers: Vec<(String, String)>,
1213
}
1314

1415
#[derive(Debug, thiserror::Error)]
@@ -35,8 +36,27 @@ impl HttpTransport {
3536
Self {
3637
client,
3738
url: url.into(),
39+
headers: vec![],
3840
}
3941
}
42+
43+
/// Consumes the current [HttpTransport] instance and returns a new one with the header
44+
/// appended. Same as calling [add_header].
45+
pub fn with_header(self, name: String, value: String) -> Self {
46+
let mut headers = self.headers;
47+
headers.push((name, value));
48+
49+
Self {
50+
client: self.client,
51+
url: self.url,
52+
headers,
53+
}
54+
}
55+
56+
/// Adds a custom HTTP header to be sent for requests.
57+
pub fn add_header(&mut self, name: String, value: String) {
58+
self.headers.push((name, value))
59+
}
4060
}
4161

4262
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
@@ -63,14 +83,16 @@ impl JsonRpcTransport for HttpTransport {
6383
let request_body = serde_json::to_string(&request_body).map_err(Self::Error::Json)?;
6484
trace!("Sending request via JSON-RPC: {}", request_body);
6585

66-
let response = self
86+
let mut request = self
6787
.client
6888
.post(self.url.clone())
6989
.body(request_body)
70-
.header("Content-Type", "application/json")
71-
.send()
72-
.await
73-
.map_err(Self::Error::Reqwest)?;
90+
.header("Content-Type", "application/json");
91+
for (name, value) in self.headers.iter() {
92+
request = request.header(name, value);
93+
}
94+
95+
let response = request.send().await.map_err(Self::Error::Reqwest)?;
7496

7597
let response_body = response.text().await.map_err(Self::Error::Reqwest)?;
7698
trace!("Response from JSON-RPC: {}", response_body);

0 commit comments

Comments
 (0)