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 client = Client::builder()
21            .timeout(config.timeout)
22            .user_agent(&config.user_agent)
23            .build()
24            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
25
26        Ok(Self { client, config })
27    }
28
29    /// Send an HTTP request
30    pub async fn send_request(&self, request: &HttpRequest) -> Result<HttpResponse, HttpError> {
31        let mut req_builder = match request.method.as_str() {
32            "GET" => self.client.get(&request.endpoint),
33            "POST" => self.client.post(&request.endpoint),
34            "PUT" => self.client.put(&request.endpoint),
35            "DELETE" => self.client.delete(&request.endpoint),
36            _ => {
37                return Err(HttpError::RequestFailed(format!(
38                    "Unsupported method: {}",
39                    request.method
40                )));
41            }
42        };
43
44        // Add headers
45        for (key, value) in &request.headers {
46            req_builder = req_builder.header(key, value);
47        }
48
49        // Add body if present
50        if let Some(body) = &request.body {
51            req_builder = req_builder.body(body.clone());
52        }
53
54        // Send request
55        let response = req_builder
56            .send()
57            .await
58            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
59
60        // Extract response data
61        let status = response.status().as_u16();
62        let headers = response
63            .headers()
64            .iter()
65            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
66            .collect::<HashMap<String, String>>();
67        let body = response
68            .text()
69            .await
70            .map_err(|e| HttpError::NetworkError(e.to_string()))?;
71
72        Ok(HttpResponse {
73            status,
74            headers,
75            body,
76        })
77    }
78
79    /// Get the configuration
80    pub fn config(&self) -> &HttpConfig {
81        &self.config
82    }
83
84    /// Get the HTTP client
85    pub fn client(&self) -> &Client {
86        &self.client
87    }
88}