Skip to content

Commit 093f87b

Browse files
committed
feat: added headers to response
Signed-off-by: Martin <martin@hotmail.com.br>
1 parent 7888214 commit 093f87b

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/infrastructure/server_impl/response.rs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::infrastructure::server_impl::server::Header;
22
use bytes::Bytes;
33
use compact_str::CompactString;
4+
use derive_more::Deref;
45
use fnv::FnvHashMap;
56
use serde::Serialize;
67
use std::fmt::Write;
@@ -24,12 +25,12 @@ pub struct Response {
2425
pub body: Option<String>,
2526
}
2627

27-
impl From<StatusCode> for Response {
28-
fn from(value: StatusCode) -> Self {
28+
impl Response {
29+
pub fn from_status_code(value: StatusCode, body: impl Into<Option<String>>) -> Self {
2930
Self {
3031
headers: Default::default(),
3132
status_code: value,
32-
body: None,
33+
body: body.into(),
3334
}
3435
}
3536
}
@@ -44,31 +45,37 @@ impl Response {
4445
write!(
4546
buf,
4647
"HTTP/1.1 {status_code} {status_message}\r\n\
47-
Content-Type: application/json; charset-utf-8\r\n\
48-
Connection: keep-alive\r\n"
48+
Server: localhost\r\n"
4949
)
5050
.expect("No reason to fail.");
5151

5252
if let Some(body) = self.body {
5353
let length = body.len();
54-
write!(buf, "Content-Length: {length}\r\n\r\n{body}").unwrap();
54+
write!(
55+
buf,
56+
"Connection: keep-alive\r\n\
57+
Content-Type: application/json; charset-utf-8\r\n\
58+
Content-Length: {length}\r\n\r\n{body}"
59+
)
60+
.unwrap();
61+
} else {
62+
write!(buf, "Connection: close\r\n").unwrap();
5563
}
5664

5765
buf.into()
5866
}
5967
}
6068

61-
#[derive(Debug)]
62-
pub struct JsonResponse(pub(crate) Response);
69+
#[derive(Debug, Deref)]
70+
pub struct JsonResponse(pub Response);
6371

6472
impl JsonResponse {
6573
pub fn from<T>(body: T) -> Self
6674
where
6775
T: Serialize,
6876
{
69-
let mut response = Response::from(StatusCode::Ok);
77+
let mut response = Response::from_status_code(StatusCode::Ok, None);
7078
let body = simd_json::to_string(&body).ok();
71-
println!("body: {:?}", body);
7279
response.body = body;
7380
Self(response)
7481
}

0 commit comments

Comments
 (0)