reqres 1.0.0

A pure Rust async HTTP client library based on Tokio with HTTP/2, connection pooling, proxy, cookie, compression, benchmarks, and comprehensive tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use std::collections::HashMap;
use bytes::Bytes;

/// HTTP 请求方法
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Method {
    GET,
    POST,
    PUT,
    DELETE,
    HEAD,
    OPTIONS,
    PATCH,
}

impl Method {
    pub fn as_str(&self) -> &'static str {
        match self {
            Method::GET => "GET",
            Method::POST => "POST",
            Method::PUT => "PUT",
            Method::DELETE => "DELETE",
            Method::HEAD => "HEAD",
            Method::OPTIONS => "OPTIONS",
            Method::PATCH => "PATCH",
        }
    }
}

/// HTTP 请求体类型
#[derive(Debug, Clone)]
pub enum Body {
    None,
    Text(String),
    Bytes(Bytes),
    Json(serde_json::Value),
}

impl Body {
    pub fn is_empty(&self) -> bool {
        matches!(self, Body::None)
    }

    pub fn as_bytes(&self) -> Vec<u8> {
        match self {
            Body::None => Vec::new(),
            Body::Text(s) => s.as_bytes().to_vec(),
            Body::Bytes(b) => b.to_vec(),
            Body::Json(v) => v.to_string().into_bytes(),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Body::None => 0,
            Body::Text(s) => s.len(),
            Body::Bytes(b) => b.len(),
            Body::Json(v) => v.to_string().len(),
        }
    }
}

/// HTTP 请求结构体
#[derive(Debug, Clone)]
pub struct Request {
    pub method: Method,
    pub url: String,
    pub headers: HashMap<String, String>,
    pub body: Body,
}

impl Request {
    /// 创建一个新的请求构建器
    pub fn builder() -> RequestBuilder {
        RequestBuilder::new()
    }

    /// 创建 GET 请求
    pub fn get(url: impl Into<String>) -> RequestBuilder {
        RequestBuilder::new().method(Method::GET).url(url)
    }

    /// 创建 POST 请求
    pub fn post(url: impl Into<String>) -> RequestBuilder {
        RequestBuilder::new().method(Method::POST).url(url)
    }

    /// 创建 PUT 请求
    pub fn put(url: impl Into<String>) -> RequestBuilder {
        RequestBuilder::new().method(Method::PUT).url(url)
    }

    /// 创建 DELETE 请求
    pub fn delete(url: impl Into<String>) -> RequestBuilder {
        RequestBuilder::new().method(Method::DELETE).url(url)
    }
}

/// 请求构建器
#[derive(Debug)]
pub struct RequestBuilder {
    method: Method,
    url: Option<String>,
    headers: HashMap<String, String>,
    body: Body,
}

impl RequestBuilder {
    /// 创建一个新的请求构建器
    pub fn new() -> Self {
        let mut headers = HashMap::new();
        headers.insert("User-Agent".to_string(), "reqres/0.2.0".to_string());
        headers.insert("Accept".to_string(), "*/*".to_string());
        headers.insert("Accept-Encoding".to_string(), "identity".to_string());

        RequestBuilder {
            method: Method::GET,
            url: None,
            headers,
            body: Body::None,
        }
    }

    /// 设置请求方法
    pub fn method(mut self, method: Method) -> Self {
        self.method = method;
        self
    }

    /// 设置请求 URL
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// 添加请求头
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// 设置请求体(文本)
    pub fn body(mut self, body: impl Into<String>) -> Self {
        let body_str = body.into();
        self.body = Body::Text(body_str);
        self.update_content_length();
        self
    }

    /// 设置请求体(Bytes)
    pub fn body_bytes(mut self, body: impl Into<Bytes>) -> Self {
        let bytes = body.into();
        self.body = Body::Bytes(bytes);
        self.update_content_length();
        self
    }

    /// 设置 JSON 请求体
    pub fn json(mut self, json: impl serde::Serialize) -> crate::Result<Self> {
        let value = serde_json::to_value(json)?;
        self.body = Body::Json(value);
        self.headers.insert("Content-Type".to_string(), "application/json".to_string());
        self.update_content_length();
        Ok(self)
    }

    /// 设置表单请求体
    pub fn form(mut self, form: &[(&str, &str)]) -> Self {
        let form_str = form
            .iter()
            .map(|(k, v)| format!("{}={}", k, v))
            .collect::<Vec<_>>()
            .join("&");
        self.body = Body::Text(form_str);
        self.headers.insert("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string());
        self.update_content_length();
        self
    }

    /// 设置 Content-Type
    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.headers.insert("Content-Type".to_string(), content_type.into());
        self
    }

    /// 更新 Content-Length 头
    fn update_content_length(&mut self) {
        if !self.body.is_empty() {
            self.headers.insert("Content-Length".to_string(), self.body.len().to_string());
        }
    }

    /// 构建请求
    pub fn build(self) -> crate::Result<Request> {
        let url = self.url.ok_or("URL is required")?;
        
        Ok(Request {
            method: self.method,
            url,
            headers: self.headers,
            body: self.body,
        })
    }
}

impl Default for RequestBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Method tests
    #[test]
    fn test_method_as_str() {
        assert_eq!(Method::GET.as_str(), "GET");
        assert_eq!(Method::POST.as_str(), "POST");
        assert_eq!(Method::PUT.as_str(), "PUT");
        assert_eq!(Method::DELETE.as_str(), "DELETE");
        assert_eq!(Method::HEAD.as_str(), "HEAD");
        assert_eq!(Method::OPTIONS.as_str(), "OPTIONS");
        assert_eq!(Method::PATCH.as_str(), "PATCH");
    }

    #[test]
    fn test_method_equality() {
        assert_eq!(Method::GET, Method::GET);
        assert_ne!(Method::GET, Method::POST);
    }

    // Body tests
    #[test]
    fn test_body_is_empty() {
        assert!(Body::None.is_empty());
        assert!(!Body::Text("test".to_string()).is_empty());
        assert!(!Body::Bytes(Bytes::from("test")).is_empty());
        assert!(!Body::Json(serde_json::json!({})).is_empty());
    }

    #[test]
    fn test_body_as_bytes() {
        assert_eq!(Body::None.as_bytes(), Vec::<u8>::new());
        assert_eq!(Body::Text("hello".to_string()).as_bytes(), b"hello");
        assert_eq!(Body::Bytes(Bytes::from(&b"world"[..])).as_bytes(), b"world");
        assert_eq!(Body::Json(serde_json::json!({"key": "value"})).as_bytes(), br#"{"key":"value"}"#);
    }

    #[test]
    fn test_body_len() {
        assert_eq!(Body::None.len(), 0);
        assert_eq!(Body::Text("hello".to_string()).len(), 5);
        assert_eq!(Body::Bytes(Bytes::from(&b"world"[..])).len(), 5);
        let json_body = Body::Json(serde_json::json!({"key": "value"}));
        // Check that length is reasonable (JSON serialization may add spaces)
        assert!(json_body.len() > 0);
        assert!(json_body.len() <= 20);
    }

    // Request tests
    #[test]
    fn test_request_builder() {
        let builder = Request::builder();
        assert_eq!(builder.method, Method::GET);
        assert_eq!(builder.url, None);
        assert!(!builder.headers.is_empty());
        matches!(builder.body, Body::None);
    }

    #[test]
    fn test_request_get() {
        let builder = Request::get("https://example.com").build().unwrap();
        assert_eq!(builder.method, Method::GET);
        assert_eq!(builder.url, "https://example.com");
    }

    #[test]
    fn test_request_post() {
        let builder = Request::post("https://example.com").build().unwrap();
        assert_eq!(builder.method, Method::POST);
        assert_eq!(builder.url, "https://example.com");
    }

    #[test]
    fn test_request_put() {
        let builder = Request::put("https://example.com").build().unwrap();
        assert_eq!(builder.method, Method::PUT);
        assert_eq!(builder.url, "https://example.com");
    }

    #[test]
    fn test_request_delete() {
        let builder = Request::delete("https://example.com").build().unwrap();
        assert_eq!(builder.method, Method::DELETE);
        assert_eq!(builder.url, "https://example.com");
    }

    // RequestBuilder tests
    #[test]
    fn test_request_builder_default() {
        let builder = RequestBuilder::default();
        assert_eq!(builder.method, Method::GET);
        assert_eq!(builder.url, None);
    }

    #[test]
    fn test_request_builder_method() {
        let builder = Request::builder().method(Method::POST);
        assert_eq!(builder.method, Method::POST);
    }

    #[test]
    fn test_request_builder_url() {
        let builder = Request::builder().url("https://example.com");
        assert_eq!(builder.url, Some("https://example.com".to_string()));
    }

    #[test]
    fn test_request_builder_header() {
        let builder = Request::builder()
            .header("X-Custom", "value")
            .header("X-Another", "test");

        assert_eq!(builder.headers.get("X-Custom"), Some(&"value".to_string()));
        assert_eq!(builder.headers.get("X-Another"), Some(&"test".to_string()));
    }

    #[test]
    fn test_request_builder_body_text() {
        let builder = Request::builder()
            .url("https://example.com")
            .body("hello world")
            .build()
            .unwrap();

        matches!(builder.body, Body::Text(_));
        assert_eq!(builder.headers.get("Content-Length"), Some(&"11".to_string()));
    }

    #[test]
    fn test_request_builder_body_bytes() {
        let bytes = Bytes::from(&b"test data"[..]);
        let builder = Request::builder()
            .url("https://example.com")
            .body_bytes(bytes.clone())
            .build()
            .unwrap();

        matches!(builder.body, Body::Bytes(_));
        assert_eq!(builder.headers.get("Content-Length"), Some(&"9".to_string()));
    }

    #[test]
    fn test_request_builder_json() {
        let data = serde_json::json!({"name": "test", "value": 42});
        let builder = Request::builder()
            .url("https://example.com")
            .json(&data)
            .unwrap()
            .build()
            .unwrap();

        matches!(builder.body, Body::Json(_));
        assert_eq!(builder.headers.get("Content-Type"), Some(&"application/json".to_string()));
    }

    #[test]
    fn test_request_builder_form() {
        let form = vec![("username", "john"), ("password", "secret")];
        let builder = Request::builder()
            .url("https://example.com")
            .form(&form)
            .build()
            .unwrap();

        matches!(builder.body, Body::Text(_));
        assert_eq!(builder.headers.get("Content-Type"), Some(&"application/x-www-form-urlencoded".to_string()));
    }

    #[test]
    fn test_request_builder_content_type() {
        let builder = Request::builder()
            .url("https://example.com")
            .content_type("text/plain")
            .build()
            .unwrap();

        assert_eq!(builder.headers.get("Content-Type"), Some(&"text/plain".to_string()));
    }

    #[test]
    fn test_request_builder_update_content_length() {
        let builder = Request::builder()
            .url("https://example.com")
            .body("test");

        assert_eq!(builder.headers.get("Content-Length"), Some(&"4".to_string()));
    }

    #[test]
    fn test_request_builder_no_content_length_on_empty() {
        let builder = Request::builder()
            .url("https://example.com")
            .build()
            .unwrap();

        assert!(builder.headers.get("Content-Length").is_none());
    }

    #[test]
    fn test_request_builder_build_success() {
        let builder = Request::builder()
            .url("https://example.com")
            .header("X-Test", "value");

        let request = builder.build().unwrap();
        assert_eq!(request.url, "https://example.com");
        assert_eq!(request.headers.get("X-Test"), Some(&"value".to_string()));
    }

    #[test]
    fn test_request_builder_build_no_url() {
        let builder = Request::builder();
        let result = builder.build();

        assert!(result.is_err());
    }

    #[test]
    fn test_request_builder_chain() {
        let request = Request::post("https://api.example.com/data")
            .header("Authorization", "Bearer token")
            .header("X-Custom", "value")
            .content_type("application/json")
            .json(&serde_json::json!({"key": "value"}))
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(request.method, Method::POST);
        assert_eq!(request.url, "https://api.example.com/data");
        assert_eq!(request.headers.get("Authorization"), Some(&"Bearer token".to_string()));
        assert_eq!(request.headers.get("X-Custom"), Some(&"value".to_string()));
        assert_eq!(request.headers.get("Content-Type"), Some(&"application/json".to_string()));
    }

    #[test]
    fn test_default_headers() {
        let builder = Request::builder().url("https://example.com").build().unwrap();
        assert!(builder.headers.contains_key("User-Agent"));
        assert!(builder.headers.contains_key("Accept"));
        assert!(builder.headers.contains_key("Accept-Encoding"));
    }
}