Skip to content
Snippets Groups Projects
Commit 844c4389 authored by codecraft's avatar codecraft :crocodile:
Browse files

Add Get request form data function

parent 677eb8a0
No related branches found
No related tags found
1 merge request!1Initial feature merge
// use std::net::SocketAddr; // use std::net::SocketAddr;
use super::{methods::Method, routes::Uri}; use std::{collections::HashMap, error::Error, fmt::Display};
use super::{
methods::Method,
routes::{Data, Uri},
};
type HeaderMap = Vec<String>; type HeaderMap = Vec<String>;
#[derive(Clone)] #[derive(Clone)]
...@@ -23,6 +28,34 @@ pub enum MediaType { ...@@ -23,6 +28,34 @@ pub enum MediaType {
Html, Html,
} }
#[derive(Debug)]
pub enum ParseErrors {
NoData,
BadData,
}
#[derive(Debug)]
pub struct ParseFormError {
pub error: ParseErrors,
}
impl Display for ParseFormError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.error)
}
}
impl Display for ParseErrors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseErrors::NoData => write!(f, "No Data at key"),
ParseErrors::BadData => write!(f, "Bad Data at key"),
}
}
}
impl Error for ParseFormError {}
impl Request<'_> { impl Request<'_> {
pub fn can_have_body(&self) -> bool { pub fn can_have_body(&self) -> bool {
match self.method { match self.method {
...@@ -30,4 +63,45 @@ impl Request<'_> { ...@@ -30,4 +63,45 @@ impl Request<'_> {
_ => false, _ => false,
} }
} }
pub fn get_form_keys(&self, keys: Vec<&str>) -> Result<HashMap<&str, &str>, ParseFormError> {
let data = self.uri.split_once("?");
if data == None {
return Err(ParseFormError {
error: ParseErrors::NoData,
});
}
let data = data
.unwrap()
.1
.split("&")
.map(|kvp| kvp.split_once("="))
.collect::<Vec<Option<(&str, &str)>>>();
let mut values: HashMap<&str, &str> = HashMap::new();
for kvp in data {
if kvp == None {
continue;
}
let kvp = kvp.unwrap();
values.insert(kvp.0, kvp.1);
}
let mut response = HashMap::new();
for key in keys {
let entry = values.get_key_value(key);
if entry == None {
return Err(ParseFormError {
error: ParseErrors::NoData,
});
}
response.insert(*entry.unwrap().0, *entry.unwrap().1);
}
Ok(response)
}
pub fn get_form_keys_with_data(
&self,
_keys: Vec<&str>,
_data_buffer: Data,
) -> Result<HashMap<&str, &str>, ParseFormError> {
todo!()
}
} }
...@@ -43,7 +43,9 @@ impl Route<'_> { ...@@ -43,7 +43,9 @@ impl Route<'_> {
} else { } else {
return false; return false;
}; };
if true_str.starts_with("<") && true_str.ends_with("..>") { if (true_str.starts_with("<") && true_str.ends_with("..>"))
|| (comp_str.starts_with(true_str) && comp_str.contains("?"))
{
return true; return true;
} }
if true_str.starts_with("<") && true_str.ends_with(">") { if true_str.starts_with("<") && true_str.ends_with(">") {
......
use std::path::PathBuf; use std::{path::PathBuf, collections::HashMap};
use http::handling::{ use http::handling::{
file_handlers::NamedFile, file_handlers::NamedFile,
...@@ -8,12 +8,26 @@ use http::handling::{ ...@@ -8,12 +8,26 @@ use http::handling::{
routes::{Data, Route}, routes::{Data, Route},
}; };
fn handle_static_hi(request: Request<'_>, data: Data) -> Outcome<Response, Status, Data> { fn hashmap_to_string(map: &HashMap<&str, &str>) -> String {
// Outcome::Success(Response { headers: vec![ let mut result = String::new();
// format!("Content-Length: 4"), for (key, value) in map {
// format!("Content-Type: text/plain") result.push_str(key);
// ], status: Some(Status::Ok), body: Box::new("jkl;") }) result.push('=');
Outcome::Forward(data) result.push_str(value);
result.push(';');
}
result.pop(); // Remove the trailing semicolon if desired
result
}
fn handle_static_hi(request: Request<'_>, _data: Data) -> Outcome<Response, Status, Data> {
let response = hashmap_to_string(&request.get_form_keys(vec!["asdf", "jkj"]).unwrap());
Outcome::Success(Response { headers: vec![
format!("Content-Length: {}", response.len()),
format!("Content-Type: text/plain")
], status: Some(Status::Ok), body: Box::new(response) })
// Outcome::Forward(data)
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment