Skip to main content

crawlkit_core/
request.rs

1//! 爬虫请求封装
2
3use std::collections::HashMap;
4
5/// 爬虫请求封装
6///
7/// 每次访问都会构造一个 Request,经过回调链后交给 HttpClient 执行。
8#[derive(Debug, Clone)]
9pub struct Request {
10    /// 目标 URL
11    pub url: String,
12    /// HTTP 方法
13    pub method: String,
14    /// 自定义请求头
15    pub headers: HashMap<String, String>,
16    /// 是否允许重复访问(跳过 visited 去重检查)
17    pub allow_revisit: bool,
18    /// 用户自定义上下文,可在回调间传递数据
19    pub context: HashMap<String, String>,
20    /// POST 请求体
21    pub body: Vec<u8>,
22    /// 是否已被回调中止(调用 `abort()` 后为 true)
23    pub aborted: bool,
24}
25
26impl Request {
27    /// 创建 GET 请求
28    pub fn get(url: &str) -> Self {
29        Self {
30            url: url.to_string(),
31            method: "GET".into(),
32            headers: HashMap::new(),
33            allow_revisit: false,
34            context: HashMap::new(),
35            body: Vec::new(),
36            aborted: false,
37        }
38    }
39
40    /// 创建 POST 请求
41    pub fn post(url: &str, body: Vec<u8>) -> Self {
42        Self {
43            url: url.to_string(),
44            method: "POST".into(),
45            headers: HashMap::new(),
46            allow_revisit: false,
47            context: HashMap::new(),
48            body,
49            aborted: false,
50        }
51    }
52
53    /// 设置请求头
54    pub fn header(mut self, key: &str, value: &str) -> Self {
55        self.headers.insert(key.to_string(), value.to_string());
56        self
57    }
58
59    /// 写入上下文键值对(回调间传递数据用)
60    pub fn set_context(mut self, key: &str, value: &str) -> Self {
61        self.context.insert(key.to_string(), value.to_string());
62        self
63    }
64
65    /// 中止当前请求处理
66    ///
67    /// 在 `on_request` 回调中调用,后续的 HTTP 请求和所有回调(on_response / on_html / on_scraped)都不会执行。
68    pub fn abort(&mut self) {
69        self.aborted = true;
70    }
71}