1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::path::Path;
mod file_parser;
mod http_parser;
pub mod request;
pub mod response;
mod threadpool;
use file_parser::FileParser;
use request::Request;
use response::Response;
use threadpool::ThreadPool;
pub struct Spot {
amount_of_threads: usize,
routes: HashMap<String, fn(Request, Response) -> Response>,
middleware: Vec<(String, fn(Request, Response) -> (Request, Response, bool))>,
}
impl Spot {
pub fn new(amount_of_threads: usize) -> Spot {
return Spot {
amount_of_threads: amount_of_threads,
routes: HashMap::new(),
middleware: Vec::new(),
};
}
pub fn middle(
&mut self,
path: &str,
function: fn(Request, Response) -> (Request, Response, bool),
) {
let mut path_string = String::from(path);
match path_string.pop() {
Some(last_char) => {
if last_char != '/' || path_string.len() == 0 {
path_string.push(last_char)
}
}
None => {
path_string.push('/');
}
};
self.middleware.push((path_string, function));
}
pub fn route(&mut self, path: &str, function: fn(Request, Response) -> Response) {
let mut path_string = String::from(path);
match path_string.pop() {
Some(last_char) => {
if last_char != '/' || path_string.len() == 0 {
path_string.push(last_char)
}
}
None => {
path_string.push('/');
}
};
if self.routes.contains_key(&path_string) {
println!(
"Warning: Route defined twice ({}), using latest definition",
path
);
self.routes.remove(&path_string);
}
self.routes.insert(path_string, function);
}
pub fn route_file(&mut self, path: &str) {
fn function(req: Request, mut res: Response) -> Response {
if req.method == "GET" {
let path = req.url;
let path_split = path.split('.');
let file_ending = match path_split.last() {
Some(file_ending) => file_ending,
None => "",
};
let file_type = FileParser::get_type(file_ending);
match fs::metadata(&path[1..]) {
Ok(metadata) => {
let mut contents = vec![0; metadata.len() as usize];
match fs::File::open(&path[1..]) {
Ok(mut file) => {
let result = file.read(&mut contents);
match result {
Ok(_) => {
res.status(200);
res.body_bytes(contents);
res.header("content-type", file_type);
}
Err(error) => {
println!("{}", error);
res.status(500);
}
}
}
Err(error) => {
println!("{}", error);
res.status(500);
}
}
}
Err(error) => {
println!("{}", error);
res.status(500);
}
}
}
return res;
};
let result = path.replace("\\", "/");
let route_path = format!("/{}", result);
Spot::route(self, &route_path, function);
}
fn add_static_files(&mut self, directory: &Path, path: &str) {
let dir_iter = fs::read_dir(path).unwrap();
for item in dir_iter {
match item {
Ok(item_uw) => {
let item_path = item_uw.path().into_os_string().into_string().unwrap();
let item_metadata = item_uw.metadata().unwrap();
if item_metadata.is_dir() {
Spot::add_static_files(self, directory, &item_path);
} else {
Spot::route_file(self, &item_path);
}
}
Err(error) => {
println!("{}", error);
}
};
}
}
pub fn public(&mut self, dir_name: &str) {
let path = env::current_dir().unwrap();
let new_root_dir = path.join(dir_name);
assert!(env::set_current_dir(&new_root_dir).is_ok());
let dir = env::current_dir().unwrap();
self.add_static_files(dir.as_path(), "");
}
pub fn bind(&mut self, ip: &str) -> String {
let listener = match TcpListener::bind(ip) {
Ok(result) => result,
Err(error) => {
return String::from(format!("Failed to bind to ip: {}", error));
}
};
self.middleware.sort_by(|a, b| a.0.len().cmp(&b.0.len()));
let routes_clone = self.routes.clone();
let middleware_clone = self.middleware.clone();
let pool = ThreadPool::new(self.amount_of_threads, routes_clone, middleware_clone);
println!("Spot server listening on: http://{}", ip);
for stream in listener.incoming() {
match stream {
Ok(stream_uw) => {
pool.execute(stream_uw);
}
Err(error) => println!("{}", error),
}
}
return String::from("Shutting down.");
}
}