Skip to main content

deribit_http/connection/
http_connection.rs

1//! HTTP connection management
2
3use crate::config::HttpConfig;
4use crate::error::HttpError;
5use crate::model::request::api_request::HttpRequest;
6use crate::model::response::api_response::HttpResponse;
7use reqwest::Client;
8use std::collections::HashMap;
9
10/// HTTP connection wrapper
11#[derive(Debug, Clone)]
12pub struct HttpConnection {
13    client: Client,
14    config: HttpConfig,
15}
16
17impl HttpConnection {
18    /// Create a new HTTP connection
19    pub fn new(config: HttpConfig) -> Result<Self, HttpError> {
20        let builder = Client::builder();
21
22        #[cfg(not(target_arch = "wasm32"))]
23        let builder = builder
24            .timeout(config.timeout)
25            .user_agent(&config.user_agent);
26
27        let client = builder
28            .build()
29            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
30
31        Ok(Self { client, config })
32    }
33
34    /// Send an HTTP request
35    pub async fn send_request(&self, request: &HttpRequest) -> Result<HttpResponse, HttpError> {
36        let mut req_builder = match request.method.as_str() {
37            "GET" => self.client.get(&request.endpoint),
38            "POST" => self.client.post(&request.endpoint),
39            "PUT" => self.client.put(&request.endpoint),
40            "DELETE" => self.client.delete(&request.endpoint),
41            _ => {
42                return Err(HttpError::RequestFailed(format!(
43                    "Unsupported method: {}",
44                    request.method
45                )));
46            }
47        };
48
49        // Add headers
50        for (key, value) in &request.headers {
51            req_builder = req_builder.header(key, value);
52        }
53
54        // Add body if present
55        if let Some(body) = &request.body {
56            req_builder = req_builder.body(body.clone());
57        }
58
59        // Send request
60        let response = req_builder
61            .send()
62            .await
63            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
64
65        // Extract response data
66        let status = response.status().as_u16();
67        let headers = response
68            .headers()
69            .iter()
70            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
71            .collect::<HashMap<String, String>>();
72        let body = response
73            .text()
74            .await
75            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
76
77        Ok(HttpResponse {
78            status,
79            headers,
80            body,
81        })
82    }
83
84    /// Get the configuration
85    pub fn config(&self) -> &HttpConfig {
86        &self.config
87    }
88
89    /// Get the HTTP client
90    pub fn client(&self) -> &Client {
91        &self.client
92    }
93}