syter6_rustful/
server.rs

1use std::net::TcpListener;
2use colored::Colorize;
3use crate::dispatcher::Dispatcher;
4use crate::models::route::Route;
5
6
7pub struct Server {
8	address: String,
9	routes: fn() -> Vec<Route>
10}
11
12impl Server {
13	pub fn new(address: &str, routes: fn() -> Vec<Route>) -> Server {
14		Server {
15			address: address.to_string(),
16			routes
17		}
18	}
19
20	pub fn run(&self) {
21		println!("Server started on {}", &self.address.blue());
22
23		// Initiate listener.
24		let listener = match TcpListener::bind(&self.address) {
25			Ok(t) => t,
26			Err(_) => panic!("Could not bind TcpListener with address {}", &self.address)
27		};
28
29		// Start listening for streams.
30		for stream in listener.incoming() {
31			let stream = match stream {
32				Ok(t) => t,
33				Err(_) => panic!("Could not find stream")
34			};
35
36			Dispatcher::dispatch(stream, self.routes)
37		}
38	}
39}