kit_rs/http/
response.rs

1use bytes::Bytes;
2use http_body_util::Full;
3
4/// HTTP Response builder providing Laravel-like response creation
5pub struct Response {
6    status: u16,
7    body: String,
8    headers: Vec<(String, String)>,
9}
10
11impl Response {
12    pub fn new() -> Self {
13        Self {
14            status: 200,
15            body: String::new(),
16            headers: Vec::new(),
17        }
18    }
19
20    /// Create a response with a string body
21    pub fn text(body: impl Into<String>) -> Self {
22        Self {
23            status: 200,
24            body: body.into(),
25            headers: vec![("Content-Type".to_string(), "text/plain".to_string())],
26        }
27    }
28
29    /// Create a JSON response
30    pub fn json(body: impl Into<String>) -> Self {
31        Self {
32            status: 200,
33            body: body.into(),
34            headers: vec![("Content-Type".to_string(), "application/json".to_string())],
35        }
36    }
37
38    /// Set the HTTP status code
39    pub fn status(mut self, status: u16) -> Self {
40        self.status = status;
41        self
42    }
43
44    /// Add a header to the response
45    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
46        self.headers.push((name.into(), value.into()));
47        self
48    }
49
50    /// Convert to hyper response
51    pub fn into_hyper(self) -> hyper::Response<Full<Bytes>> {
52        let mut builder = hyper::Response::builder().status(self.status);
53
54        for (name, value) in self.headers {
55            builder = builder.header(name, value);
56        }
57
58        builder
59            .body(Full::new(Bytes::from(self.body)))
60            .unwrap()
61    }
62}
63
64impl Default for Response {
65    fn default() -> Self {
66        Self::new()
67    }
68}