From 4504a9b77b068685a06ea659cb542defc100e8e2 Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Thu, 5 Jan 2023 12:44:52 +0100 Subject: [PATCH] Add Status enum to handle status codes cleanly --- src/ear.rs | 1 + src/mouth.rs | 31 ++++++++++++++++++++++--------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/ear.rs b/src/ear.rs index 354deb9..c02cca8 100644 --- a/src/ear.rs +++ b/src/ear.rs @@ -39,6 +39,7 @@ impl Ear { let req = self.receive_request(&stream); let req = parse_url(req); + return (stream, req.unwrap()); } diff --git a/src/mouth.rs b/src/mouth.rs index 058eb85..5f984a6 100644 --- a/src/mouth.rs +++ b/src/mouth.rs @@ -1,25 +1,38 @@ //! Holds the elements pertaining to Mouth, a sender object. -use std::{io::Write, net::TcpStream}; +use std::{fmt::Display, io::Write, net::TcpStream}; use serde_json::Value; -/// Corresponds to a sender object. -pub struct Mouth { - stream: TcpStream, +pub enum Status { + OK, + NotFound, } -impl Mouth { - pub fn new(stream: TcpStream) -> Self { +impl Display for Status { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Status::OK => write!(f, "HTTP/1.1 200 OK"), + Status::NotFound => write!(f, "HTTP/1.1 404 NOT FOUND"), + } + } +} + +/// Corresponds to a sender object. +pub struct Mouth<'a> { + stream: &'a TcpStream, +} + +impl<'a> Mouth<'a> { + pub fn new(stream: &'a TcpStream) -> Self { Self { stream } } /// Send response data in JSON to a client. - pub fn send_data(&mut self, data: Value) { - let status_line = "HTTP/1.1 200 OK"; + pub fn send_data(&mut self, status_code: Status, data: Value) { let contents = data.to_string(); let length = contents.len(); - let response = format!("{status_line}\r\nContent-Type: application/json\r\nContent-Length: {length}\r\n\r\n{contents}"); + let response = format!("{status_code}\r\nContent-Type: application/json\r\nContent-Length: {length}\r\n\r\n{contents}"); self.stream.write_all(response.as_bytes()).unwrap(); }