Skip to main content

aria2_protocol/http/
request.rs

1#[derive(Debug, Clone)]
2pub struct HttpRequest {
3    pub method: String,
4    pub url: String,
5    pub headers: Option<Vec<(String, String)>>,
6    pub body: Option<Vec<u8>>,
7}
8
9impl HttpRequest {
10    pub fn new<U: Into<String>>(method: &str, url: U) -> Self {
11        Self {
12            method: method.to_string(),
13            url: url.into(),
14            headers: None,
15            body: None,
16        }
17    }
18
19    pub fn get<U: Into<String>>(url: U) -> Self {
20        Self::new("GET", url)
21    }
22
23    pub fn post<U: Into<String>>(url: U) -> Self {
24        Self::new("POST", url)
25    }
26
27    pub fn head<U: Into<String>>(url: U) -> Self {
28        Self::new("HEAD", url)
29    }
30
31    pub fn with_header(mut self, name: &str, value: &str) -> Self {
32        self.headers
33            .get_or_insert_with(Vec::new)
34            .push((name.to_string(), value.to_string()));
35        self
36    }
37
38    pub fn with_headers(mut self, headers: Vec<(String, String)>) -> Self {
39        self.headers = Some(headers);
40        self
41    }
42
43    pub fn with_body(mut self, body: Vec<u8>) -> Self {
44        self.body = Some(body);
45        self
46    }
47
48    pub fn with_body_str(mut self, body: &str) -> Self {
49        self.body = Some(body.as_bytes().to_vec());
50        self
51    }
52
53    pub fn with_range(self, start: u64, end: Option<u64>) -> Self {
54        let range_value = match end {
55            Some(e) => format!("bytes={}-{}", start, e),
56            None => format!("bytes={}-", start),
57        };
58        self.with_header("Range", &range_value)
59    }
60
61    pub fn with_user_agent(self, ua: &str) -> Self {
62        self.with_header("User-Agent", ua)
63    }
64
65    pub fn with_referer(self, referer: &str) -> Self {
66        self.with_header("Referer", referer)
67    }
68
69    pub fn with_accept_encoding(self, encoding: &str) -> Self {
70        self.with_header("Accept-Encoding", encoding)
71    }
72
73    pub fn get_header(&self, name: &str) -> Option<&String> {
74        self.headers
75            .as_ref()?
76            .iter()
77            .find(|(k, _)| k.eq_ignore_ascii_case(name))
78            .map(|(_, v)| v)
79    }
80
81    pub fn has_range(&self) -> bool {
82        self.get_header("Range").is_some()
83    }
84}