Decode incoming request url

This commit is contained in:
flyingscorpio@clevo 2023-01-05 17:13:33 +01:00
parent 652ab3686e
commit ab3ac277e7
3 changed files with 16 additions and 4 deletions

7
Cargo.lock generated
View file

@ -229,6 +229,7 @@ dependencies = [
"serde_json",
"tokio",
"url",
"urlencoding",
]
[[package]]
@ -873,6 +874,12 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "urlencoding"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
[[package]]
name = "vcpkg"
version = "0.2.15"

View file

@ -11,3 +11,4 @@ serde_json = "1.0.89"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
url = "2.3.1"
urlencoding = "2.1.2"

View file

@ -4,6 +4,8 @@ use core::str::Split;
use std::io::{prelude::*, BufReader};
use std::net::{TcpListener, TcpStream};
use urlencoding::decode;
use crate::database::search_title;
use crate::mouth::{Mouth, Status};
@ -46,7 +48,7 @@ impl Ear {
let req = self.extract_first_line_of_request(&stream);
let mut sender = Mouth::new(&stream);
match parse_url(&req) {
match parse_uri(&req) {
Ok(req) => handle_request(req, sender),
Err(req) => sender.send_data(
Status::BadRequest,
@ -58,7 +60,7 @@ impl Ear {
/// Handles a given incoming stream.
/// A request is supposed to be a REST API call from a client.
/// Forwards the received request to `parse_url`.
/// Forwards the received request to `parse_uri`.
fn extract_first_line_of_request(&self, mut stream: &TcpStream) -> String {
let buf_reader = BufReader::new(&mut stream);
let http_request = buf_reader.lines().next().unwrap().unwrap();
@ -69,13 +71,15 @@ impl Ear {
/// Receives and parses a request from `receive_request` to dermine the function to call.
/// We are expecting the request to be like 'GET /api/titre/jean'
fn parse_url(full_request: &str) -> Result<Request, ReqParseError> {
fn parse_uri(full_request: &str) -> Result<Request, ReqParseError> {
let method: String = full_request.split_whitespace().nth(0).unwrap().to_string();
let uri = full_request.split_whitespace().nth(1).unwrap();
let uri = decode(uri).expect("UTF-8").to_string();
if let 3 = uri.chars().filter(|c| *c == '/').count() {
let section: String = uri.split("/").nth(2).unwrap().to_string();
let requested_data: String = uri.split("/").nth(3).unwrap().to_string();
let requested_data = uri.split("/").nth(3).unwrap().to_string();
let request = Request {
method,
section,