luciders/src/http/responses.rs

60 lines
1.4 KiB
Rust

use std::error::Error;
use std::io::prelude::*;
use std::net::TcpStream;
pub struct Response<'a> {
stream: &'a mut TcpStream,
pub status: u16,
}
impl<'a> Response<'a> {
pub fn new(stream: &'a mut TcpStream, status: u16) -> Self {
Response {
stream,
status,
}
}
pub fn send(&mut self) -> UnitOrBoxedError {
send_response(self.stream, self.status, "")
}
}
pub type UnitOrBoxedError = Result<(), Box<dyn Error>>;
pub fn send_response(mut stream: &TcpStream, status: u16, body: &str) -> UnitOrBoxedError {
let status_line = match status {
200 => "HTTP/1.1 200 OK",
400 => "HTTP/1.1 400 BAD REQUEST",
404 => "HTTP/1.1 404 NOT FOUND",
405 => "HTTP/1.1 405 METHOD NOT ALLOWED",
_ => "HTTP/1.1 500 INTERNAL SERVER ERROR",
};
let response = format!(
"{}\r\nContent-Length: {}\r\nServer: luciders/0.1.0\r\n\r\n{}",
status_line,
body.len(),
body
);
match stream.write(response.as_bytes()) {
Ok(_) => {}
Err(e) => {
return Err(Box::new(e));
}
}
match stream.flush() {
Ok(_) => {}
Err(e) => {
return Err(Box::new(e));
}
}
Ok(())
}
pub fn ok(stream: &TcpStream, body: &str) -> UnitOrBoxedError {
send_response(stream, 200, body)
}