Add Status enum to handle status codes cleanly
This commit is contained in:
parent
6c9112a10c
commit
4504a9b77b
2 changed files with 23 additions and 9 deletions
|
@ -39,6 +39,7 @@ impl Ear {
|
||||||
|
|
||||||
let req = self.receive_request(&stream);
|
let req = self.receive_request(&stream);
|
||||||
let req = parse_url(req);
|
let req = parse_url(req);
|
||||||
|
|
||||||
return (stream, req.unwrap());
|
return (stream, req.unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
31
src/mouth.rs
31
src/mouth.rs
|
@ -1,25 +1,38 @@
|
||||||
//! Holds the elements pertaining to Mouth, a sender object.
|
//! 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;
|
use serde_json::Value;
|
||||||
|
|
||||||
/// Corresponds to a sender object.
|
pub enum Status {
|
||||||
pub struct Mouth {
|
OK,
|
||||||
stream: TcpStream,
|
NotFound,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Mouth {
|
impl Display for Status {
|
||||||
pub fn new(stream: TcpStream) -> Self {
|
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 }
|
Self { stream }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send response data in JSON to a client.
|
/// Send response data in JSON to a client.
|
||||||
pub fn send_data(&mut self, data: Value) {
|
pub fn send_data(&mut self, status_code: Status, data: Value) {
|
||||||
let status_line = "HTTP/1.1 200 OK";
|
|
||||||
let contents = data.to_string();
|
let contents = data.to_string();
|
||||||
let length = contents.len();
|
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();
|
self.stream.write_all(response.as_bytes()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue