Add Status enum to handle status codes cleanly

This commit is contained in:
flyingscorpio@clevo 2023-01-05 12:44:52 +01:00
parent 6c9112a10c
commit 4504a9b77b
2 changed files with 23 additions and 9 deletions

View file

@ -39,6 +39,7 @@ impl Ear {
let req = self.receive_request(&stream);
let req = parse_url(req);
return (stream, req.unwrap());
}

View file

@ -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();
}