Skip to content
Closed
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
21 changes: 17 additions & 4 deletions src/lib/http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,21 @@ impl Server {
let mut found_path = false;

for (key, value) in self.handlers.get(&request.method).unwrap() {
if request.is_similar(key) {
request.parse_args(key);

// self.handlers - это HashMap<Method, HashMap<String, HandlerFn>> (поле struct Server)

// self.handlers.get(&request.method)
// попытка найти на 1м уровне HashMap запись по ключу типа Method
// например .get(POST) ищу на 1м уровне HashMap table ключ = Method::POST
// возвращает Option<&HashMap<String, HandlerFn>>
// если запись есть, возвращается Some(HashMap<String, HanlerFn>)
// если нет, возвращаю None

// .unwrap() достаёт ссылку на значение из 1-го уровня HashMap table (т.е. из Some) => &HashMap<String, HandlerFn>

// Далее происходит итерирование по 2му уровню HashMap table
if request.is_exact(key) {
request.parse_args();

let response = value(&request);
let deserialized_response = deser_response(response);
Expand All @@ -359,8 +372,8 @@ impl Server {
let _ = stream.write_all(deser_response(BAD_REQUEST_RESPONSE).as_bytes());
}
}
Err(e) => {
eprintln!("Failed to establish connection: {e}") // :(
Err(error) => {
eprintln!("Failed to establish connection: {error}") // :(
}
}
}
Expand Down
40 changes: 33 additions & 7 deletions src/lib/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,45 @@ impl Default for Request {
}

impl Request {
pub fn parse_args(&mut self, path: &str) {
let request_chunks: Vec<&str> = self.path.split("/").collect();
// /container/:id/reboot разбивается на ["", "container", ":id", "reboot"]
// функция для парсинга (т.е. разбиения) пути по составляющим
pub fn parse_args(&mut self) {
let request_chunks: Vec<&str> = self.path.trim_start_matches('/').split('/').collect();
// /container/:id/reboot разбивается на [ container, :id, reboot ] т.к. убрали начальное / .trim_start_matches
for (i, &key_chunk) in request_chunks.iter().enumerate() {
// .iter - получаю итератор, .enumerate - добавляю текущему итератору counter (счетчик)
if key_chunk.starts_with(":") {
// подходит key_chunk = ":id"
let (_, id) = key_chunk.split_at(1); // получаем: ":" и "id" (":" выкидываем т.к. первый аргумент _)
self.rest_params
.insert(id.to_string(), request_chunks[i].to_string()); // вставляем в Hash-table<String, String> элемент <1, id>
}
}
}

for (i, key_chunk) in path.split("/").enumerate() {
if i == 0 {
continue;
/*
pub fn parse_args(&mut self) {
let mut request_chunks: Vec<&str> = self.path.split("/").collect(); // /container/:id/reboot разбивается на ["", "container", ":id", "reboot"]
request_chunks.remove(0); // убираю пустой сегмент "", имеем => ["container", ":id", "reboot"]

for (i, key_chunk) in request_chunks.into_iter().enumerate() {
// .iter - получаю итератор, .enumerate - добавляю текущему итератору counter (счетчик)
if key_chunk.starts_with(":") {
// подходит key_chunk = ":id"
let (_, id) = key_chunk.split_at(1); // получаем: ":" и "id" (":" выкидываем т.к. первый аргумент _)
self.rest_params
.insert(id.to_string(), request_chunks[i].to_string()); // вставляем в Hash-table<String, String> элемент <1, id>
}
}
/*
for (i, key_chunk) in path.split("/").enumerate() {
if key_chunk.starts_with(":") {
let (_, id) = key_chunk.split_at(1);
self.rest_params
.insert(id.to_string(), request_chunks[i].to_string());
}
}
}
}*/
}*/

// ПРОВИРЯЕТ ЧТО ПУТЬ ИЗ РЕКВЕСТА И ПУТЬ ИЗ АРГУМЕНТА АНАЛОГИЧНЫ
// НЕ СЧИТАЯ ВСЯКИХ ТАМ АРГУМЕНТОВ
Expand Down Expand Up @@ -80,6 +105,7 @@ mod tests {
.rest_params
.insert("id".to_string(), "label".to_string());


request.parse_args(path);
assert!(request.is_similar(path));
assert_eq!(request, expected_request);
Expand Down
Loading