Skip to main content

coman/core/
http_response.rs

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