rust_integration_services/http/
http_response.rs

1use std::collections::HashMap;
2
3use crate::http::http_status::HttpStatus;
4
5#[derive(Debug, Clone)]
6pub struct HttpResponse {
7    pub status: HttpStatus,
8    pub headers: HashMap<String, String>,
9    pub body: Vec<u8>,
10}
11
12impl HttpResponse {
13    pub fn new() -> Self {
14        HttpResponse {
15            status: HttpStatus::Ok,
16            headers: HashMap::new(),
17            body: Vec::new(),
18        }
19    }
20
21    /// Creates a http response with status 200
22    pub fn ok() -> Self {
23        HttpResponse::new().status(200)
24    }
25    
26    /// Creates a http response with status 302
27    pub fn found() -> Self {
28        HttpResponse::new().status(302)
29    }
30    
31    /// Creates a http response with status 400
32    pub fn bad_request() -> Self {
33        HttpResponse::new().status(400)
34    }
35    
36    /// Creates a http response with status 401
37    pub fn unauthorized() -> Self {
38        HttpResponse::new().status(401)
39    }
40    
41    /// Creates a http response with status 403
42    pub fn forbidden() -> Self {
43        HttpResponse::new().status(403)
44    }
45    
46    /// Creates a http response with status 404
47    pub fn not_found() -> Self {
48        HttpResponse::new().status(404)
49    }
50    
51    /// Creates a http response with status 500
52    pub fn internal_server_error() -> Self {
53        HttpResponse::new().status(500)
54    }
55
56    /// Sets the HTTP response status code.
57    pub fn status(mut self, code: u16) -> Self {
58        self.status = HttpStatus::from_code(code).expect("Invalid HTTP status code");
59        self
60    }
61
62    /// Adds or updates a header in the HTTP response.
63    pub fn header<T: AsRef<str>>(mut self, key: T, value: T) -> Self {
64        self.headers.insert(key.as_ref().to_string(), value.as_ref().to_string());
65        self
66    }
67
68    /// Sets the HTTP response body and automatically adds a `content-length` header.
69    pub fn body(mut self, body: &[u8]) -> Self {
70        self.body = body.to_vec();
71        self.headers.insert(String::from("content-length"), String::from(body.len().to_string()));
72        self
73    }
74}