diff options
author | Tyler Murphy <tylerm@tylerm.dev> | 2023-07-02 22:15:24 -0400 |
---|---|---|
committer | Tyler Murphy <tylerm@tylerm.dev> | 2023-07-02 22:15:24 -0400 |
commit | 41fe16978ea506127bf43c21e977fd9581d87282 (patch) | |
tree | b5bf1ef7a37404350d45f0b6e8a00c5b32216e08 /src/main.rs | |
parent | more info (diff) | |
download | bashttp-41fe16978ea506127bf43c21e977fd9581d87282.tar.gz bashttp-41fe16978ea506127bf43c21e977fd9581d87282.tar.bz2 bashttp-41fe16978ea506127bf43c21e977fd9581d87282.zip |
add methods to routes, allow custom headers and response codes
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 70 |
1 files changed, 12 insertions, 58 deletions
diff --git a/src/main.rs b/src/main.rs index 9cf8e90..0f7dc59 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,69 +1,23 @@ -use std::collections::HashMap; -use std::sync::Arc; -use http::code::Code; -use http::header::Header; -use http::request::Request; -use http::response::Response; -use tokio::net::{TcpListener, TcpStream}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; - -use crate::bash::handle_script; +use std::{env, sync::Arc}; +use tokio::net::TcpListener; +use crate::server::handle_connection; mod http; -mod bash; - -async fn handle_response(mut socket: TcpStream, code: Code, body: String) { - let mut res = Response::new(); - res.headers.put(Header::new("Content-Type", "text/plain")); - res.status = code; - res.body = Some(body); - - let res_str = res.deserialize(); - - let _ = socket.write(res_str.as_bytes()).await; -} +mod script; +mod server; -async fn handle_connection(mut socket: TcpStream, config: Arc<HashMap<String, String>>) { - - let mut buf = [0; 1204]; +#[tokio::main] +async fn main() { - let n: usize = match socket.read(&mut buf).await { - Ok(n) if n == 0 => return, - Ok(n) => n as usize, - Err(e) => { - eprintln!("failed to read from socket; err = {:?}", e); + let config = match script::Config::load() { + Ok(config) => Arc::new(config), + Err(err) => { + eprintln!("failed to load config: {err}"); return } }; - - let str = String::from_utf8_lossy(&buf[0..n]); - - let Some(req) = Request::serialize(&str) else { - return - }; - - - let Some(script) = config.get(&req.uri.route) else { - handle_response(socket, Code::MethodNotAllowed, "Method Not Allowed".to_owned()).await; - return - }; - - match handle_script(script, req.body.as_ref()) { - Ok(out) => { - handle_response(socket, Code::Success, out).await; - }, - Err(err) => { - handle_response(socket, Code::MethodNotAllowed, err).await; - }, - } -} - -#[tokio::main] -async fn main() { - - let config = Arc::new(bash::load_config()); - let port = std::env::var("PORT") + let port = env::var("PORT") .unwrap_or_else(|_| String::from("8080")) .parse::<u16>() .unwrap_or_else(|_| 8080); |