coman/core/
http_response.rs

1use std::collections::HashMap;
2
3/// HTTP Response
4#[derive(Debug, Clone)]
5pub struct HttpResponse {
6    /// HTTP Version
7    pub version: String,
8    /// Response status code
9    pub status: u16,
10    /// Response status text
11    pub status_text: String,
12    /// Response headers
13    pub headers: HashMap<String, String>,
14    /// Response body as string
15    pub body: String,
16    /// Response body as bytes (for binary data)
17    // pub body_bytes: Vec<u8>,
18    /// Request duration in milliseconds
19    pub elapsed_ms: u128,
20    /// Final URL (after redirects)
21    pub url: String,
22}
23
24impl HttpResponse {
25    /// Check if the response status is successful (2xx)
26    pub fn is_success(&self) -> bool {
27        (200..300).contains(&self.status)
28    }
29
30    /// Check if the response status is a redirect (3xx)
31    pub fn is_redirect(&self) -> bool {
32        (300..400).contains(&self.status)
33    }
34
35    /// Check if the response status is a client error (4xx)
36    pub fn is_client_error(&self) -> bool {
37        (400..500).contains(&self.status)
38    }
39
40    /// Check if the response status is a server error (5xx)
41    pub fn is_server_error(&self) -> bool {
42        (500..600).contains(&self.status)
43    }
44
45    /// Try to parse the response body as JSON
46    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
47        serde_json::from_str(&self.body)
48    }
49}