aria2_protocol/http/
response.rs1use tracing::debug;
2
3#[derive(Debug, Clone)]
4pub struct HttpResponse {
5 pub status_code: u16,
6 pub status_text: String,
7 pub headers: Vec<(String, String)>,
8 pub body: Vec<u8>,
9}
10
11impl HttpResponse {
12 pub fn new(status_code: u16, status_text: String) -> Self {
13 Self {
14 status_code,
15 status_text,
16 headers: Vec::new(),
17 body: Vec::new(),
18 }
19 }
20
21 pub fn is_success(&self) -> bool {
22 (200..300).contains(&self.status_code)
23 }
24
25 pub fn is_redirect(&self) -> bool {
26 [300, 301, 302, 303, 307, 308].contains(&self.status_code)
30 }
31
32 pub fn is_partial_content(&self) -> bool {
33 self.status_code == 206
34 }
35
36 pub fn is_client_error(&self) -> bool {
37 (400..500).contains(&self.status_code)
38 }
39
40 pub fn is_server_error(&self) -> bool {
41 (500..600).contains(&self.status_code)
42 }
43
44 pub fn header(&self, name: &str) -> Option<&String> {
45 self.headers
46 .iter()
47 .find(|(k, _)| k.eq_ignore_ascii_case(name))
48 .map(|(_, v)| v)
49 }
50
51 pub fn header_all(&self, name: &str) -> Vec<&String> {
52 self.headers
53 .iter()
54 .filter(|(k, _)| k.eq_ignore_ascii_case(name))
55 .map(|(_, v)| v)
56 .collect()
57 }
58
59 pub fn content_length(&self) -> Option<u64> {
60 self.header("content-length")
61 .and_then(|v| v.parse::<u64>().ok())
62 }
63
64 pub fn content_type(&self) -> Option<&str> {
65 self.header("content-type").map(|s| s.as_str())
66 }
67
68 pub fn content_encoding(&self) -> Option<&str> {
69 self.header("content-encoding").map(|s| s.as_str())
70 }
71
72 pub fn content_disposition(&self) -> Option<&str> {
73 self.header("content-disposition").map(|s| s.as_str())
74 }
75
76 pub fn accept_ranges(&self) -> bool {
77 self.header("accept-ranges")
78 .map(|v| v.eq_ignore_ascii_case("bytes"))
79 .unwrap_or(false)
80 }
81
82 pub fn location(&self) -> Option<&str> {
83 self.header("location").map(|s| s.as_str())
84 }
85
86 pub fn etag(&self) -> Option<&str> {
87 self.header("etag").map(|s| s.as_str())
88 }
89
90 pub fn last_modified(&self) -> Option<&str> {
91 self.header("last-modified").map(|s| s.as_str())
92 }
93
94 pub fn server(&self) -> Option<&str> {
95 self.header("server").map(|s| s.as_str())
96 }
97
98 pub fn connection(&self) -> Option<&str> {
99 self.header("connection").map(|s| s.as_str())
100 }
101
102 pub fn transfer_encoding(&self) -> Option<&str> {
103 self.header("transfer-encoding").map(|s| s.as_str())
104 }
105
106 pub fn body_as_utf8(&self) -> Result<&str, std::str::Utf8Error> {
107 std::str::from_utf8(&self.body)
108 }
109
110 pub fn body_len(&self) -> usize {
111 self.body.len()
112 }
113
114 pub fn parse_content_range(&self) -> Option<ContentRange> {
115 let raw = self.header("content-range")?;
116 ContentRange::parse(raw)
117 }
118}
119
120#[derive(Debug, Clone, PartialEq)]
121pub struct ContentRange {
122 pub unit: String,
123 pub start: u64,
124 pub end: u64,
125 pub total_size: Option<u64>,
126}
127
128impl ContentRange {
129 pub fn parse(value: &str) -> Option<Self> {
130 let value = value.trim();
131 if !value.starts_with("bytes ") {
132 debug!("Content-Range format error: not 'bytes' unit");
133 return None;
134 }
135
136 let range_part = &value[6..];
137 let parts: Vec<&str> = range_part.split('/').collect();
138 if parts.len() != 2 {
139 debug!("Content-Range format error: split failed");
140 return None;
141 }
142
143 let range_values: Vec<&str> = parts[0].split('-').collect();
144 if range_values.len() != 2 {
145 debug!("Content-Range range parse failed");
146 return None;
147 }
148
149 let start: u64 = range_values[0].trim().parse().ok()?;
150 let end: u64 = range_values[1].trim().parse().ok()?;
151 let total_size = match parts[1].trim() {
152 "*" => None,
153 s => s.parse().ok(),
154 };
155
156 Some(Self {
157 unit: "bytes".to_string(),
158 start,
159 end,
160 total_size,
161 })
162 }
163
164 pub fn size(&self) -> u64 {
165 self.end - self.start + 1
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use crate::http::request::HttpRequest;
173
174 #[test]
175 fn test_response_status_checks() {
176 let resp_ok = HttpResponse::new(200, "OK".into());
177 assert!(resp_ok.is_success());
178 assert!(!resp_ok.is_redirect());
179 assert!(!resp_ok.is_partial_content());
180
181 let resp_206 = HttpResponse::new(206, "Partial Content".into());
182 assert!(resp_206.is_success());
183 assert!(resp_206.is_partial_content());
184
185 let resp_301 = HttpResponse::new(301, "Moved".into());
186 assert!(resp_301.is_redirect());
187
188 let resp_404 = HttpResponse::new(404, "Not Found".into());
189 assert!(resp_404.is_client_error());
190
191 let resp_500 = HttpResponse::new(500, "Server Error".into());
192 assert!(resp_500.is_server_error());
193 }
194
195 #[test]
196 fn test_headers_lookup() {
197 let mut resp = HttpResponse::new(200, "OK".into());
198 resp.headers
199 .push(("Content-Length".to_string(), "1024".to_string()));
200 resp.headers.push((
201 "Content-Type".to_string(),
202 "application/octet-stream".to_string(),
203 ));
204
205 assert_eq!(resp.content_length(), Some(1024));
206 assert_eq!(resp.content_type(), Some("application/octet-stream"));
207 assert_eq!(resp.header("content-length"), Some(&"1024".to_string()));
208 }
209
210 #[test]
211 fn test_content_range_parse() {
212 let cr = ContentRange::parse("bytes 0-499/1000").unwrap();
213 assert_eq!(cr.start, 0);
214 assert_eq!(cr.end, 499);
215 assert_eq!(cr.total_size, Some(1000));
216 assert_eq!(cr.size(), 500);
217
218 let cr_unknown_total = ContentRange::parse("bytes 0-499/*").unwrap();
219 assert_eq!(cr_unknown_total.total_size, None);
220
221 assert!(ContentRange::parse("invalid").is_none());
222 assert!(ContentRange::parse("bits 0-499/1000").is_none());
223 }
224
225 #[test]
226 fn test_request_builder() {
227 let req = HttpRequest::get("https://example.com/file.bin")
228 .with_range(500, Some(999))
229 .with_user_agent(crate::identity::DEFAULT_USER_AGENT);
230
231 assert_eq!(req.method, "GET");
232 assert!(req.has_range());
233 assert_eq!(req.get_header("Range"), Some(&"bytes=500-999".to_string()));
234 assert_eq!(
235 req.get_header("User-Agent"),
236 Some(&crate::identity::DEFAULT_USER_AGENT.to_string())
237 );
238 }
239}