Skip to content

Commit

Permalink
feat: refact codebase and use match on tcp listener accept in server lib
Browse files Browse the repository at this point in the history
  • Loading branch information
Ando committed Feb 9, 2024
1 parent daad8e2 commit 753723b
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 18 deletions.
5 changes: 0 additions & 5 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@ impl Handler {
pub fn handle_connection(mut tcp_stream: TcpStream, router: &Box<dyn Fn(&[u8]) + Send + Sync>) {

Check warning on line 14 in src/handler.rs

View workflow job for this annotation

GitHub Actions / lint

very complex type used. Consider factoring parts into `type` definitions

Check warning on line 14 in src/handler.rs

View workflow job for this annotation

GitHub Actions / lint

very complex type used. Consider factoring parts into `type` definitions
loop {
let mut buffer = [0; 1028];

match tcp_stream.read(&mut buffer) {
Ok(stream_count) => {
if stream_count == 0 {
break;
}

let request = &buffer[0..stream_count];
router(request);

println!("{}", Handler::get_request_path(request));
}
Err(e) => panic!("{}", e),
Expand All @@ -35,7 +32,6 @@ impl Handler {
if let Err(e) = ctrlc::set_handler(move || {
exit.store(true, Ordering::SeqCst);
println!("Ctrl + C pressed. Exiting gracefully...");

process::exit(0);
}) {
panic!("{}", e);
Expand All @@ -45,7 +41,6 @@ impl Handler {
pub fn get_request_path(request: &[u8]) -> String {
let request_str = String::from_utf8_lossy(request);
let request_lines: Vec<&str> = request_str.lines().collect();

let request_path = request_lines
.first()
.unwrap_or(&"")
Expand Down
3 changes: 0 additions & 3 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use regex::Regex;
pub fn is_empty(host: &str, port: u32) -> bool {
let is_host_empty = host.is_empty();
let is_port_empty = port == 0;

match (is_host_empty, is_port_empty) {

Check warning on line 7 in src/params.rs

View workflow job for this annotation

GitHub Actions / lint

match expression looks like `matches!` macro

Check warning on line 7 in src/params.rs

View workflow job for this annotation

GitHub Actions / lint

match expression looks like `matches!` macro
(true, true) => true,
_ => false,
Expand All @@ -13,7 +12,6 @@ pub fn is_empty(host: &str, port: u32) -> bool {

pub fn is_valid_local_host(host: &str) -> bool {
let pattern = constants::HOST_REGEX;

match Regex::new(pattern) {
Ok(re) => re.is_match(host),
Err(_) => false,
Expand All @@ -22,7 +20,6 @@ pub fn is_valid_local_host(host: &str) -> bool {

pub fn is_valid_port(port: u32) -> bool {
let pattern = constants::PORT_REGEX;

match Regex::new(pattern) {
Ok(re) => re.is_match(&port.to_string()),
Err(_) => false,
Expand Down
15 changes: 5 additions & 10 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ impl Server {
F: Fn(&[u8]) + Send + Sync + 'static,
{
self.initialize();

self
.routes
.lock()
Expand All @@ -44,36 +43,32 @@ impl Server {

pub fn listen(&self, host: &str, port: u32) {
self.initialize();

validator::validate_host_and_port(host, port);

let addr = format!("{}:{}", host, port);

let term = Arc::new(AtomicBool::new(false));

self::Handler::handle_exit_process(Arc::clone(&term).clone());

println!("App is listening on {}", &addr);

let listener = TcpListener::bind(&addr).expect("An error occured while listening app");
let listener = TcpListener::bind(&addr).unwrap();
match listener.accept() {
Ok((_socket, _addr)) => println!("App is listening on {}", &addr),
Err(e) => println!("An error occured while listening app with error, {}", e),
}

for stream in listener.incoming() {
if term.load(Ordering::SeqCst) {
println!("Exiting thread...");

break;
}

match stream {
Ok(tcp_stream) => {
let routes_clone = Arc::clone(&self.routes);

thread::spawn(move || {
let routes_lock = routes_clone.lock().unwrap();
let router = routes_lock.get("/").unwrap_or_else(|| {
panic!("An error occurred, no handler found for default route");
});

Handler::handle_connection(tcp_stream, router);
});
}
Expand Down

0 comments on commit 753723b

Please sign in to comment.