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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
#![allow(unused)]
use http_server_starter_rust::router::Router;
use itertools::Itertools;
use nom::AsBytes;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::str::Utf8Error;
use std::sync::{Arc, Mutex};
use std::{str, thread, usize};
use http_server_starter_rust::request::*;
use http_server_starter_rust::response::*;
use http_server_starter_rust::{extractor, http_types::*};
fn save_bytes_to_file(bytes: &[u8], file_path: &str) -> io::Result<()> {
let mut file = File::create(file_path)?;
file.write_all(bytes)?;
Ok(())
}
fn read_file_as_bytes(path: &str) -> io::Result<Vec<u8>> {
// Open the file in read-only mode
let mut file = File::open(path)?;
// Create a buffer to hold the file contents
let mut buffer = Vec::new();
// Read the file contents into the buffer
file.read_to_end(&mut buffer)?;
// Return the buffer
Ok(buffer)
}
fn handle_echo(request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
let mut headers = HashMap::new();
// Extract the route regardless of the variant
let mut echo_string = "".to_string();
let route = match request.method() {
Method::Get(route) | Method::Post(route) | Method::Put(route) => route,
};
for ch in route.chars().skip(1).skip_while(|&ch| ch != '/').skip(1) {
echo_string.push(ch);
}
if echo_string.chars().last().unwrap() == '/' {
echo_string.pop();
}
let len = echo_string.len().to_string();
headers.insert("Content-Type".to_string(), "text/plain".to_string());
headers.insert("Content-Length".to_string(), len);
let body = echo_string;
Response::new(
"1.1".to_string(),
StatusCode::Ok,
Some(Headers(headers)),
Some(body),
)
}
fn handle_post_files(request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
// Extract the route regardless of the variant
let mut file = "".to_string();
let route = match request.method() {
Method::Get(route) | Method::Post(route) | Method::Put(route) => route,
};
let mut directory = ctx.unwrap().get(&"dir".to_string()).unwrap().clone();
directory.pop(); // remove last slash
for ch in route.chars().skip(1).skip_while(|&ch| ch != '/') {
file.push(ch);
}
if file.chars().last().unwrap() == '/' {
file.pop();
}
let len = file.len().to_string();
let full_path = &(directory + &file);
println!("post_files");
dbg!(full_path);
let bytes = request.body().as_ref().unwrap();
let body = bytes.as_bytes();
match save_bytes_to_file(body, full_path) {
Ok(bytes) => Response::new("1.1".to_string(), StatusCode::Created, None, None),
Err(err) => {
println!("Error: {err}");
Response::new("1.1".to_string(), StatusCode::NotFound, None, None)
}
}
}
fn handle_files(request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
// Extract the route regardless of the variant
let mut file = "".to_string();
let route = match request.method() {
Method::Get(route) | Method::Post(route) | Method::Put(route) => route,
};
let mut directory = ctx.unwrap().get(&"dir".to_string()).unwrap().clone();
directory.pop(); // remove last slash
for ch in route.chars().skip(1).skip_while(|&ch| ch != '/') {
file.push(ch);
}
if file.chars().last().unwrap() == '/' {
file.pop();
}
let len = file.len().to_string();
let full_path = &(directory + &file);
println!("handle_files");
dbg!(full_path);
match read_file_as_bytes(full_path) {
Ok(bytes) => {
let mut headers = HashMap::new();
headers.insert(
"Content-Type".to_string(),
"application/octet-stream".to_string(),
);
headers.insert("Content-Length".to_string(), bytes.len().to_string());
let body = String::from_utf8(bytes).unwrap();
Response::new(
"1.1".to_string(),
StatusCode::Ok,
Some(Headers(headers)),
Some(body),
)
}
Err(_) => Response::new("1.1".to_string(), StatusCode::NotFound, None, None),
}
}
fn handle_user_agent(request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
let mut headers = HashMap::new();
let user_agent = request.get_tag("User-Agent".to_string());
let len = user_agent.len().to_string();
headers.insert("Content-Type".to_string(), "text/plain".to_string());
headers.insert("Content-Length".to_string(), len);
let body = user_agent.to_string();
Response::new(
"1.1".to_string(),
StatusCode::Ok,
Some(Headers(headers)),
Some(body),
)
.into()
}
fn handle_success(request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
Response::new("1.1".to_string(), StatusCode::Ok, None, None).into()
}
fn handle_not_found(request: Request, ctx: Option<&HashMap<String, String>>) -> Response {
Response::new("1.1".to_string(), StatusCode::NotFound, None, None).into()
}
fn serve(
mut stream: TcpStream,
router: Arc<Mutex<Router>>,
ctx: Arc<Mutex<HashMap<String, String>>>,
) -> io::Result<usize> {
// Buffer to store the data received from the client
let mut buffer = [0; 512];
// Read data from the stream
match stream.read(&mut buffer) {
Ok(_) => {
// Convert buffer to a string and print the received data
match str::from_utf8(&buffer) {
Ok(request) => {
use Method::*;
println!("Received request:\n{}", request);
let request_lines: Vec<&str> = request.split("\r\n").collect();
dbg!(&request_lines);
let request = Request::from(request_lines);
let request_string: String = (&request).into();
println!("body:\n{:?}", request.body());
let response: String = {
let router = router.lock().unwrap();
let ctx = ctx.lock().unwrap();
router.handle(&request, Some(&ctx)).into()
};
stream.write(response.as_bytes())
}
Err(_) => todo!(),
}
}
Err(_) => todo!(),
}
}
fn main() -> io::Result<()> {
// Collect the command-line arguments
let args: Vec<String> = std::env::args().collect();
let mut dir = "".to_string();
let ctx<
|