summaryrefslogtreecommitdiff
path: root/src/response.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/response.rs')
-rw-r--r--src/response.rs71
1 files changed, 49 insertions, 22 deletions
diff --git a/src/response.rs b/src/response.rs
index 801e682..fa1a294 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -1,48 +1,75 @@
+mod builder;
+
+use get::Get;
+
+use std::collections::HashMap;
+
use tokio::{
fs::File,
io::{self, AsyncWrite, AsyncWriteExt},
};
+use strum::Display;
+
+use builder::Builder;
+
+#[allow(unreachable_patterns)]
+#[derive(Debug, Clone, Copy, Display)]
+pub enum Status {
+ #[strum(to_string = "200 OK")]
+ Ok,
+
+ #[strum(to_string = "404 Not Found")]
+ NotFound,
+
+ #[strum(to_string = "500 Internal Server Error")]
+ InternalServerError,
+}
+
#[derive(Debug)]
pub enum Body {
File(File),
- Bytes(Vec<u8>),
+ Buffer(Vec<u8>),
Empty,
}
-#[derive(Debug)]
-pub struct Response(http::Response<Body>);
+#[derive(Debug, Get)]
+pub struct Response {
+ status: Status,
+ headers: HashMap<String, Vec<u8>>,
+ body: Body,
+}
impl Response {
- pub fn new(inner: http::Response<Body>) -> Self {
- Self(inner)
- }
-
- pub fn inner(&self) -> &http::Response<Body> {
- &self.0
+ pub fn builder() -> Builder {
+ Builder::new()
}
}
impl Response {
- pub async fn to_wire<W: AsyncWrite + Unpin>(self, writer: &mut W) -> io::Result<()> {
- writer
- .write_all(format!("HTTP/1.1 {}\r\n", self.0.status()).as_bytes())
- .await?;
-
- for (key, value) in self.0.headers() {
- writer.write_all(format!("{key}: ").as_bytes()).await?;
- writer.write_all(value.as_bytes()).await?;
+ pub async fn serialize<W: AsyncWrite + Unpin>(
+ mut self,
+ mut writer: W,
+ ) -> Result<(), io::Error> {
+ writer.write_all(b"HTTP/1.1 ").await?;
+ writer.write_all(self.status.to_string().as_bytes()).await?;
+ writer.write_all(b"\r\n").await?;
+
+ for (key, value) in &self.headers {
+ writer.write_all(key.as_bytes()).await?;
+ writer.write_all(b": ").await?;
+ writer.write_all(value).await?;
writer.write_all(b"\r\n").await?;
}
writer.write_all(b"\r\n").await?;
- match self.0.into_body() {
- Body::File(mut file) => {
- io::copy(&mut file, writer).await?;
+ match &mut self.body {
+ Body::File(file) => {
+ io::copy(file, &mut writer).await?;
}
- Body::Bytes(buf) => {
- writer.write_all(&buf).await?;
+ Body::Buffer(buf) => {
+ writer.write_all(buf).await?;
}
Body::Empty => (),
}