aboutsummaryrefslogtreecommitdiff
path: root/src/http_types.rs
diff options
context:
space:
mode:
authoromagdy7 <omar.professional8777@gmail.com>2024-06-03 20:40:54 +0300
committeromagdy7 <omar.professional8777@gmail.com>2024-06-03 20:40:54 +0300
commit4f9d09b58ae81e4e6144b85ce36ba424e319b779 (patch)
tree3b85a7f352928ba0ff05678ba3fb2341f16361ce /src/http_types.rs
parent66f3fcdf0fe097e37b9e3dc8d1a984c35b4d34a4 (diff)
downloadtiny-server-4f9d09b58ae81e4e6144b85ce36ba424e319b779.tar.xz
tiny-server-4f9d09b58ae81e4e6144b85ce36ba424e319b779.zip
codecrafters submit [skip ci]
Diffstat (limited to 'src/http_types.rs')
-rw-r--r--src/http_types.rs77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/http_types.rs b/src/http_types.rs
new file mode 100644
index 0000000..a652e6c
--- /dev/null
+++ b/src/http_types.rs
@@ -0,0 +1,77 @@
+use itertools::Itertools;
+use std::collections::HashMap;
+
+pub enum StatusCode {
+ // 2xx Success
+ Ok,
+
+ // 4xx Client Error
+ BadRequest,
+ NotFound,
+}
+
+type Endpoint = String;
+type Target = String;
+
+#[derive(Debug)]
+pub enum HTTPMethod {
+ Get((Endpoint, Target)),
+ Post((Endpoint, Target)),
+ Put((Endpoint, Target)),
+}
+
+impl From<StatusCode> for String {
+ fn from(val: StatusCode) -> Self {
+ use StatusCode::*;
+ match val {
+ Ok => "200 OK".to_string(),
+ BadRequest => "400 Bad Request".to_string(),
+ NotFound => "404 Not Found".to_string(),
+ }
+ }
+}
+
+impl From<HTTPMethod> for String {
+ fn from(val: HTTPMethod) -> Self {
+ use HTTPMethod::*;
+ match val {
+ Get((endpoint, target)) => "GET".to_string() + &endpoint + &target,
+ Post((endpoint, target)) => "POST".to_string() + &endpoint + &target,
+ Put((endpoint, target)) => "PUT".to_string() + &endpoint + &target,
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Headers(pub HashMap<String, String>);
+
+impl From<&[&str]> for Headers {
+ fn from(value: &[&str]) -> Self {
+ let mut header_map = HashMap::new();
+ for header in value.iter().filter(|val| !val.is_empty()) {
+ let (key, val) = header
+ .split_once(": ")
+ .expect("Should be splitable by :<space>");
+ header_map.insert(key.to_string(), val.to_string());
+ }
+ Headers(header_map)
+ }
+}
+
+impl From<&str> for HTTPMethod {
+ fn from(val: &str) -> Self {
+ use HTTPMethod::*;
+ let request_line = val.split(' ').collect_vec();
+ let (method, info) = (request_line[0], request_line[1]);
+ let info = info.chars().skip(1).collect::<String>() + &"/";
+ let (endpoint, target) = info.split_once("/").expect("Should be splitable by /");
+ match method {
+ "GET" => Get((endpoint.to_string(), target.to_string())),
+ "POST" => Post((endpoint.to_string(), target.to_string())),
+ _ => {
+ eprintln!("{method} Not Supported Yet");
+ unreachable!()
+ }
+ }
+ }
+}