http_endpoint_server_harness/entities/
request.rs1use std::collections::HashMap;
2
3#[derive(Debug, Clone)]
5pub struct Request {
6 pub method: super::Method,
7 pub path: String,
8 pub headers: HashMap<String, String>,
9 pub body: Vec<u8>,
10}
11
12impl Request {
13 pub fn new(method: super::Method, path: impl Into<String>) -> Self {
14 Self {
15 method,
16 path: path.into(),
17 headers: HashMap::new(),
18 body: Vec::new(),
19 }
20 }
21
22 pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
23 self.headers.insert(key.into(), value.into());
24 self
25 }
26
27 pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
28 self.body = body.into();
29 self
30 }
31
32 pub fn body_as_str(&self) -> Option<&str> {
33 std::str::from_utf8(&self.body).ok()
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40 use crate::entities::Method;
41 use std::collections::HashMap;
42
43 #[test]
44 fn test_request_body_as_str() {
45 let request = Request {
46 method: Method::Post,
47 path: "/test".to_string(),
48 headers: HashMap::new(),
49 body: b"Hello World".to_vec(),
50 };
51 assert_eq!(request.body_as_str(), Some("Hello World"));
52 }
53
54 #[test]
55 fn test_request_body_as_str_invalid_utf8() {
56 let request = Request {
57 method: Method::Post,
58 path: "/test".to_string(),
59 headers: HashMap::new(),
60 body: vec![0xFF, 0xFE],
61 };
62 assert_eq!(request.body_as_str(), None);
63 }
64
65 #[test]
66 fn test_request_method_display() {
67 assert_eq!(format!("{}", Method::Get), "GET");
68 assert_eq!(format!("{}", Method::Post), "POST");
69 assert_eq!(format!("{}", Method::Put), "PUT");
70 assert_eq!(format!("{}", Method::Delete), "DELETE");
71 }
72}
73