Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: re-struct package to be an http core server for rust #29

Merged
merged 2 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
[package]
name = "core"
name = "http_core"
version = "0.1.0"
edition = "2021"
description = "A lightweight server core for Rust"
description = "A lightweight http server core for Rust"
categories = ["http-server"]
keywords = ["core", "server", "http", "minimalist", "lightweight"]
authors = ["Ando <[email protected]>"]
license = "MIT"
repository = "https://github.com/exprust/core"
repository = "https://github.com/rusticore/http-core"

[lib]
name = "core"
name = "http_core"
path = "src/lib.rs"

[dependencies]
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<p align="center">
<img
src="./assets/logo-banner.png"
alt="Exprust"
alt="Http Core"
style="width:100%;"
/>
</p>

![build](https://github.com/exprust/core/workflows/build/badge.svg)
![license](https://img.shields.io/github/license/exprust/core?color=success)
![build](https://github.com/rusticore/http-core/workflows/build/badge.svg)
![license](https://img.shields.io/github/license/rusticore/http-core?color=success)

A lightweight server core for Rust
A lightweight http server core for Rust

## License

Expand Down
2 changes: 1 addition & 1 deletion examples/hello_lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::server::Server;
use http_core::server::Server;

const HELLO_WORLD_HTML: &str = r#"
<!DOCTYPE html>
Expand Down
5 changes: 0 additions & 5 deletions src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,16 @@
pub struct Handler {}

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 @@
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 @@
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,8 +4,7 @@
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_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_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 @@ -12,11 +12,11 @@

pub struct Server {
initialized: bool,
routes: Arc<Mutex<HashMap<String, Box<dyn Fn(&[u8]) + Send + Sync>>>>,

Check warning on line 15 in src/server.rs

View workflow job for this annotation

GitHub Actions / lint

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

Check warning on line 15 in src/server.rs

View workflow job for this annotation

GitHub Actions / lint

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

impl Server {
pub fn new() -> Self {

Check warning on line 19 in src/server.rs

View workflow job for this annotation

GitHub Actions / lint

you should consider adding a `Default` implementation for `Server`

Check warning on line 19 in src/server.rs

View workflow job for this annotation

GitHub Actions / lint

you should consider adding a `Default` implementation for `Server`
Server {
initialized: true,
routes: Arc::new(Mutex::new(HashMap::new())),
Expand All @@ -34,7 +34,6 @@
F: Fn(&[u8]) + Send + Sync + 'static,
{
self.initialize();

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

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
2 changes: 1 addition & 1 deletion tests/lib_spec.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[cfg(test)]
mod params {
use core::params;
use http_core::params;

#[test]
fn is_empty() {
Expand Down
Loading