Skip to content

Commit 1be1148

Browse files
committed
first commit
0 parents  commit 1be1148

File tree

18 files changed

+640
-0
lines changed

18 files changed

+640
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/target
2+
/Cargo.lock
3+
4+
/dev/note/private

Cargo.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "rust-http-web-lib"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
regex = "1.6.0"

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# sharhttp-rs

debug/.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/target
2+
/Cargo.lock
3+
4+
/dev/note/private

debug/Cargo.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "debug"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
rust-http-web-lib={path="../"}

debug/src/main.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use rust_http_web_lib::routeManager::RouterManager;
2+
use rust_http_web_lib::App::HttpHandler;
3+
use rust_http_web_lib::Request::get_http_data::HeaderData;
4+
use rust_http_web_lib::Response::ResponseTool;
5+
6+
use std::net::TcpListener;
7+
8+
fn main() {
9+
let mut handle = HttpHandler::new();
10+
const PORT: i32 = 8000;
11+
12+
handle.get("/".to_owned(), home_handler);
13+
handle.all(log_request);
14+
let mut new_route = HttpHandler::new();
15+
new_route.get("/".to_owned(), home_handler);
16+
17+
handle.route("/sub".to_string(), &new_route);
18+
let listener = TcpListener::bind(format!("127.0.0.1:{PORT}"));
19+
match listener {
20+
Ok(listener) => {
21+
println!(
22+
"máy chủ bật rồi đó ở cổng {} link đi đến đó nè http://{}",
23+
PORT,
24+
listener.local_addr().unwrap()
25+
);
26+
handle.handle_http_request(listener);
27+
}
28+
Err(err) => {
29+
panic!("{}", err);
30+
}
31+
}
32+
}
33+
fn home_handler(_request: &HeaderData, response: &mut ResponseTool, _: &mut RouterManager) {
34+
response.send("<h1>hello world</h1>".to_string(), true);
35+
}
36+
fn log_request(request: &HeaderData, _response: &mut ResponseTool, _: &mut RouterManager) {
37+
println!("method: {}, path: {}", request.method, request.path);
38+
}

src/App/mod.rs

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
#![allow(dead_code)]
2+
use std::{collections::HashMap, net::TcpListener};
3+
4+
use crate::{
5+
routeManager::RouterManager, util::append_vec::append_vec, HandleConnection::RequestProcessing,
6+
Request::get_http_data::HeaderData, Response::ResponseTool,
7+
};
8+
9+
pub type HandleCallback = fn(&HeaderData, &mut ResponseTool, &mut RouterManager) -> (); // request: HeaderData, response: TcpStream
10+
pub type HandlerType = HashMap<HandlerHashmapKeyString, Vec<HandleCallback>>;
11+
#[derive(Clone)]
12+
pub struct HttpHandler {
13+
handler: HandlerType,
14+
not_found_handler: HandleCallback,
15+
threading: bool,
16+
}
17+
18+
pub fn default_not_found_handler(
19+
_req: &HeaderData,
20+
response: &mut ResponseTool,
21+
_: &mut RouterManager,
22+
) {
23+
let not_found_contents = "<h1>404 Page Not Found</h1>";
24+
response.status(404);
25+
response.send(not_found_contents.to_string(), true);
26+
}
27+
28+
impl HttpHandler {
29+
pub fn new() -> HttpHandler {
30+
return HttpHandler {
31+
handler: (HashMap::new()),
32+
not_found_handler: default_not_found_handler,
33+
threading: false,
34+
};
35+
}
36+
37+
pub fn turn_threading(&mut self) -> &mut Self {
38+
self.threading = !self.threading;
39+
self
40+
}
41+
42+
pub fn post(&mut self, path: String, handler: HandleCallback) {
43+
let key = get_key("POST".to_string(), path);
44+
self.add_handle(key, handler);
45+
}
46+
47+
pub fn get(&mut self, path: String, handler: HandleCallback) {
48+
let key = get_key("GET".to_string(), path);
49+
self.add_handle(key, handler);
50+
}
51+
52+
pub fn put(&mut self, path: String, handler: HandleCallback) {
53+
let key = get_key("PUT".to_owned(), path);
54+
self.add_handle(key, handler);
55+
}
56+
57+
pub fn patch(&mut self, path: String, handler: HandleCallback) {
58+
let key = get_key("PATCH".to_string(), path);
59+
self.add_handle(key, handler);
60+
}
61+
pub fn delete(&mut self, path: String, handler: HandleCallback) {
62+
let key = get_key("DELETE".to_string(), path);
63+
self.add_handle(key, handler);
64+
}
65+
pub fn all_method(&mut self, path: String, handler: HandleCallback) {
66+
let key = get_key("*".to_string(), path);
67+
self.add_handle(key, handler);
68+
}
69+
pub fn not_found(&mut self, handler: HandleCallback) {
70+
self.not_found_handler = handler;
71+
}
72+
pub fn all(&mut self, handler: HandleCallback) {
73+
let key = get_key("*".to_string(), "*".to_string());
74+
self.add_handle(key, handler);
75+
}
76+
pub fn handle_http_request(&mut self, listener: TcpListener) {
77+
for stream in listener.incoming() {
78+
let mut stream = stream.unwrap();
79+
let mut process = RequestProcessing::new(self.not_found_handler);
80+
process.preProcessing(&self.handler, &mut stream);
81+
if self.threading {
82+
let han = &mut self.handler;
83+
std::thread::spawn(move || process.processing(&mut stream))
84+
.join()
85+
.and_then(|f| {
86+
f.ProcessingRouter(han);
87+
Ok(())
88+
})
89+
.expect("đen thôi đỏ là red");
90+
} else {
91+
process
92+
.processing(&mut stream)
93+
.ProcessingRouter(&mut self.handler);
94+
}
95+
// stream
96+
// .shutdown(std::net::Shutdown::Both)
97+
// .expect("shutdown call failed");
98+
}
99+
}
100+
101+
pub fn handlers(&self) -> &HandlerType {
102+
&self.handler
103+
}
104+
pub fn route(&mut self, path: String, route: &Self) {
105+
self.add_route(path, route)
106+
}
107+
}
108+
109+
trait Handle {
110+
fn add_handle(&mut self, key: HandlerHashmapKeyString, handler: HandleCallback);
111+
fn add_multiple_handler(&mut self, key: HandlerHashmapKeyString, handler: Vec<HandleCallback>);
112+
}
113+
impl Handle for HttpHandler {
114+
fn add_handle(&mut self, key: HandlerHashmapKeyString, handler: HandleCallback) {
115+
self.add_multiple_handler(key, vec![handler])
116+
}
117+
118+
fn add_multiple_handler(&mut self, key: HandlerHashmapKeyString, handler: Vec<HandleCallback>) {
119+
pub_add_multiple_handler(&mut self.handler, key, handler);
120+
}
121+
}
122+
123+
pub fn pub_add_multiple_handler(
124+
handlers: &mut HandlerType,
125+
key: HandlerHashmapKeyString,
126+
handler: Vec<HandleCallback>,
127+
) {
128+
let handle = handlers.get_mut(&key);
129+
match handle {
130+
Some(handle) => append_vec(handle, &handler),
131+
None => {
132+
handlers.insert(key, handler);
133+
}
134+
}
135+
}
136+
pub fn get_key(method: String, path: String) -> HandlerHashmapKeyString {
137+
let key = format!("{}{}", method, path);
138+
return HandlerHashmapKeyString {
139+
data: key,
140+
method,
141+
path,
142+
};
143+
}
144+
#[derive(Clone, Eq, Hash, PartialEq)]
145+
pub struct HandlerHashmapKeyString {
146+
pub data: String,
147+
pub method: String,
148+
pub path: String,
149+
}
150+
151+
trait Router {
152+
fn add_route(&mut self, path: String, route: &Self);
153+
}
154+
impl Router for HttpHandler {
155+
fn add_route(&mut self, path: String, route: &Self) {
156+
add_route_pub(&mut self.handler, path, route.handlers());
157+
}
158+
}
159+
160+
pub fn add_route_pub(hander: &mut HandlerType, path: String, route: &HandlerType) {
161+
for n in route.keys() {
162+
let mut new_path = path.clone();
163+
new_path.push_str(
164+
&(match new_path.ends_with("/") {
165+
true => n.path.clone(),
166+
false => match n.path.starts_with("/") {
167+
true => n.path.clone(),
168+
false => "/".to_owned() + &n.path,
169+
},
170+
}),
171+
);
172+
let key = get_key(n.method.clone(), new_path);
173+
pub_add_multiple_handler(hander, key, route.get(n).unwrap().to_vec());
174+
}
175+
}

src/HandleConnection/mod.rs

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
#![allow(dead_code)]
2+
use std::{
3+
collections::HashMap,
4+
io::{BufRead, BufReader},
5+
net::TcpStream,
6+
};
7+
8+
use crate::{
9+
routeManager::RouterManager,
10+
util::append_vec::append_vec,
11+
App::{get_key, HandlerType},
12+
Request::get_http_data::{GetRequest, HeaderData},
13+
Response::ResponseTool,
14+
};
15+
16+
use crate::App::HandleCallback;
17+
18+
pub struct RequestProcessing {
19+
ProcessingHandler: Vec<HandleCallback>,
20+
not_found_handler: HandleCallback,
21+
httpData: HeaderData,
22+
}
23+
24+
impl RequestProcessing {
25+
pub fn new(not_found_handler: HandleCallback) -> RequestProcessing {
26+
RequestProcessing {
27+
ProcessingHandler: Vec::new(),
28+
not_found_handler,
29+
httpData: HeaderData::Default(),
30+
}
31+
}
32+
pub fn preProcessing(&mut self, handlers: &HandlerType, stream: &mut TcpStream) {
33+
self.get_request_data(stream);
34+
self.get_handler(handlers);
35+
}
36+
pub fn processing(&mut self, stream: &mut TcpStream) -> RouterManager {
37+
self.handle_connection(stream)
38+
}
39+
}
40+
41+
pub trait HandleConnection {
42+
fn handle_connection(&mut self, stream: &mut TcpStream) -> RouterManager;
43+
fn get_request_data(&mut self, stream: &TcpStream);
44+
fn get_handler(&mut self, handlers: &HandlerType);
45+
}
46+
impl HandleConnection for RequestProcessing {
47+
fn handle_connection(&mut self, stream: &mut TcpStream) -> RouterManager {
48+
let mut response = ResponseTool {
49+
stream,
50+
response: false,
51+
status: 200,
52+
content: "".to_string(),
53+
header: &mut HashMap::new(),
54+
Request: self.httpData.clone(),
55+
cookie: &mut Vec::new(),
56+
};
57+
let mut routerM = RouterManager::new();
58+
59+
routerM.setLocalPath(self.httpData.path.clone());
60+
response.Setup();
61+
62+
if self.ProcessingHandler.len() <= 0 {
63+
(self.not_found_handler)(&self.httpData, &mut response, &mut routerM);
64+
return routerM;
65+
};
66+
67+
for h in &self.ProcessingHandler {
68+
if response.response {
69+
return routerM;
70+
}
71+
(&h)(&self.httpData, &mut response, &mut routerM);
72+
}
73+
if response.response {
74+
return routerM;
75+
}
76+
(self.not_found_handler)(&self.httpData, &mut response, &mut routerM);
77+
return routerM;
78+
}
79+
80+
fn get_request_data(&mut self, stream: &TcpStream) {
81+
let http_request: Vec<_> = BufReader::new(stream.try_clone().unwrap())
82+
.lines()
83+
.map(|result| result.unwrap())
84+
.take_while(|line| !line.is_empty())
85+
.collect();
86+
self.httpData = GetRequest(&http_request);
87+
}
88+
89+
fn get_handler(&mut self, handlers: &HandlerType) {
90+
let path_use = String::from(format!(
91+
"{}",
92+
format_args!(
93+
"{}{}",
94+
self.httpData.path.clone(),
95+
match self.httpData.path.ends_with("/") {
96+
true => "*",
97+
false => "/*",
98+
}
99+
)
100+
));
101+
let mut path_list: Vec<String> =
102+
vec!["*".to_string(), path_use, self.httpData.path.clone()];
103+
if !self.httpData.path.clone().ends_with("/") {
104+
path_list.push(format!("{}/", self.httpData.path.clone()));
105+
}
106+
107+
let method_list = vec!["*", &self.httpData.method];
108+
for path in path_list {
109+
for method in &method_list {
110+
let key = get_key(method.to_string(), path.to_string());
111+
if handlers.contains_key(&key) {
112+
let rest_handlers = handlers.get(&key).unwrap();
113+
append_vec(&mut self.ProcessingHandler, rest_handlers);
114+
}
115+
}
116+
}
117+
}
118+
}

src/Request/get_default_header.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
use super::get_http_data::HeaderType;
2+
3+
4+
pub fn default_header(header: &HeaderType) -> &HeaderType {
5+
header
6+
}

0 commit comments

Comments
 (0)