From d6420aacaf4dde328e98bcdf9ef163bcf2462492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=A4=E9=9B=A8=E4=B8=9C?= Date: Sun, 22 Dec 2024 09:23:46 +0800 Subject: [PATCH] feat:dependencies --- Cargo.lock | 68 ++++++++++-- Cargo.toml | 5 +- src/compress/brotli/decode.rs | 23 ---- src/compress/brotli/mod.rs | 1 - src/compress/constant.rs | 14 --- src/compress/deflate/decode.rs | 21 ---- src/compress/deflate/mod.rs | 1 - src/compress/gzip/decode.rs | 28 ----- src/compress/gzip/mod.rs | 1 - src/compress/impl.rs | 73 ------------- src/compress/mod.rs | 6 -- src/compress/type.rs | 7 -- src/constant/common.rs | 50 --------- src/constant/mod.rs | 3 +- src/constant/{request.rs => type.rs} | 6 ++ src/content_type/impl.rs | 155 --------------------------- src/content_type/mod.rs | 2 - src/content_type/type.rs | 22 ---- src/http_url/impl.rs | 47 -------- src/http_url/mod.rs | 2 - src/http_url/type.rs | 27 ----- src/http_version/impl.rs | 20 ---- src/http_version/mod.rs | 2 - src/http_version/type.rs | 20 ---- src/lib.rs | 7 -- src/methods/constant.rs | 2 - src/methods/impl.rs | 43 -------- src/methods/mod.rs | 3 - src/methods/type.rs | 10 -- src/protocol/impl.rs | 75 ------------- src/protocol/mod.rs | 2 - src/protocol/type.rs | 14 --- src/request/config/impl.rs | 8 +- src/request/config/type.rs | 6 +- src/request/constant.rs | 76 ------------- src/request/header/mod.rs | 1 - src/request/header/type.rs | 6 -- src/request/mod.rs | 2 - src/request/request/impl.rs | 33 ++---- src/request/request/type.rs | 6 +- src/request/request_builder/impl.rs | 7 +- src/response/mod.rs | 1 - src/response/response_binary/impl.rs | 8 +- src/response/response_binary/type.rs | 4 +- src/response/response_header/mod.rs | 1 - src/response/response_header/type.rs | 6 -- src/response/response_text/impl.rs | 9 +- src/response/response_text/type.rs | 4 +- src/status_code/impl.rs | 106 ------------------ src/status_code/mod.rs | 2 - src/status_code/type.rs | 42 -------- src/utils/vec.rs | 2 +- 52 files changed, 105 insertions(+), 985 deletions(-) delete mode 100644 src/compress/brotli/decode.rs delete mode 100644 src/compress/brotli/mod.rs delete mode 100644 src/compress/constant.rs delete mode 100644 src/compress/deflate/decode.rs delete mode 100644 src/compress/deflate/mod.rs delete mode 100644 src/compress/gzip/decode.rs delete mode 100644 src/compress/gzip/mod.rs delete mode 100644 src/compress/impl.rs delete mode 100644 src/compress/mod.rs delete mode 100644 src/compress/type.rs delete mode 100644 src/constant/common.rs rename src/constant/{request.rs => type.rs} (57%) delete mode 100644 src/content_type/impl.rs delete mode 100644 src/content_type/mod.rs delete mode 100644 src/content_type/type.rs delete mode 100644 src/http_url/impl.rs delete mode 100644 src/http_url/mod.rs delete mode 100644 src/http_url/type.rs delete mode 100644 src/http_version/impl.rs delete mode 100644 src/http_version/mod.rs delete mode 100644 src/http_version/type.rs delete mode 100644 src/methods/constant.rs delete mode 100644 src/methods/impl.rs delete mode 100644 src/methods/mod.rs delete mode 100644 src/methods/type.rs delete mode 100644 src/protocol/impl.rs delete mode 100644 src/protocol/mod.rs delete mode 100644 src/protocol/type.rs delete mode 100644 src/request/constant.rs delete mode 100644 src/request/header/mod.rs delete mode 100644 src/request/header/type.rs delete mode 100644 src/response/response_header/mod.rs delete mode 100644 src/response/response_header/type.rs delete mode 100644 src/status_code/impl.rs delete mode 100644 src/status_code/mod.rs delete mode 100644 src/status_code/type.rs diff --git a/Cargo.lock b/Cargo.lock index fd1de58..76dfc44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -163,14 +163,39 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http-compress" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c9fccf894ecce94e49dc4e7a2dee74e3663d1bf77b241c9a6b1efcec3e127e6" +dependencies = [ + "brotli", + "flate2", + "http-constant", + "http-type 0.0.4", +] + +[[package]] +name = "http-constant" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "838fe2d468592d5b45b432a26f2217fb473e6f48d7e12e4ddaa4a08ae846db15" +dependencies = [ + "brotli", + "flate2", +] + [[package]] name = "http-request" -version = "8.0.2" +version = "8.1.0" dependencies = [ "brotli", "color-output", "flate2", "hex", + "http-compress", + "http-constant", + "http-type 1.0.0", "native-tls", "serde", "serde-xml-rs", @@ -181,6 +206,35 @@ dependencies = [ "urlencoding", ] +[[package]] +name = "http-type" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca2c92f65244b2202e859bda54325da9d881ffe751bb435a302adb071fba5a" +dependencies = [ + "hex", + "http-constant", + "serde", + "serde-xml-rs", + "serde_json", + "serde_urlencoded", +] + +[[package]] +name = "http-type" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "307ca5f8ed7666e9fdf63f382427c7d8451a3b22e5742c7f1b64937d63b02453" +dependencies = [ + "hex", + "http-constant", + "serde", + "serde-xml-rs", + "serde_json", + "serde_urlencoded", + "url", +] + [[package]] name = "icu_collections" version = "1.5.0" @@ -515,9 +569,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e" dependencies = [ "serde_derive", ] @@ -536,9 +590,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", @@ -547,9 +601,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.133" +version = "1.0.134" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" dependencies = [ "itoa", "memchr", diff --git a/Cargo.toml b/Cargo.toml index 98d8c46..b5e5424 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "http-request" -version = "8.0.2" +version = "8.1.0" edition = "2021" authors = ["ltpp-universe "] license = "MIT" @@ -19,6 +19,9 @@ exclude = [ brotli = "7.0.0" flate2 = "1.0.35" hex = "0.4.3" +http-compress = "0.0.2" +http-constant = "1.2.0" +http-type = "1.0.0" native-tls = "0.2.12" serde = { version = "1.0", features = ["derive"] } serde-xml-rs = "0.6.0" diff --git a/src/compress/brotli/decode.rs b/src/compress/brotli/decode.rs deleted file mode 100644 index 0e753f4..0000000 --- a/src/compress/brotli/decode.rs +++ /dev/null @@ -1,23 +0,0 @@ -use brotli::Decompressor; -use std::io::Read; - -/// Decodes compressed data using a specified decompressor -/// -/// This function takes a reference to a `Vec` containing compressed data and a buffer size. -/// It uses the `Decompressor` to decompress the data and returns the decompressed result as a `Vec`. -/// If decompression fails, it returns an empty `Vec`. -/// -/// # Parameters -/// - `data`: A reference to a `Vec` containing the compressed data. -/// - `buffer_size`: The buffer size to use for the decompressor. -/// -/// # Returns -/// A `Vec` containing the decompressed data, or an empty `Vec` if decompression fails. -pub fn decode(data: &Vec, buffer_size: usize) -> Vec { - let mut decompressor: Decompressor<&[u8]> = Decompressor::new(data.as_slice(), buffer_size); - let mut decompressed_data: Vec = Vec::new(); - match decompressor.read_to_end(&mut decompressed_data) { - Ok(_) => decompressed_data, - _ => Vec::new(), - } -} diff --git a/src/compress/brotli/mod.rs b/src/compress/brotli/mod.rs deleted file mode 100644 index 5ac80bb..0000000 --- a/src/compress/brotli/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod decode; diff --git a/src/compress/constant.rs b/src/compress/constant.rs deleted file mode 100644 index 96b91a8..0000000 --- a/src/compress/constant.rs +++ /dev/null @@ -1,14 +0,0 @@ -/// A constant representing the "gzip" compression algorithm. -/// -/// This constant holds the string value `"gzip"`, which is commonly used to refer to the GZIP compression format. -pub static GZIP: &str = "gzip"; - -/// A constant representing the "deflate" compression algorithm. -/// -/// This constant holds the string value `"deflate"`, which is commonly used to refer to the DEFLATE compression format. -pub static DEFLATE: &str = "deflate"; - -/// A constant representing the "br" compression algorithm (Brotli). -/// -/// This constant holds the string value `"br"`, which is commonly used to refer to the Brotli compression format. -pub static BR: &str = "br"; diff --git a/src/compress/deflate/decode.rs b/src/compress/deflate/decode.rs deleted file mode 100644 index bf36482..0000000 --- a/src/compress/deflate/decode.rs +++ /dev/null @@ -1,21 +0,0 @@ -use flate2::read::DeflateDecoder; -use std::io::{BufReader, Read}; - -/// Decodes deflate compressed data -/// -/// # Parameters -/// - `data`: A reference to a `Vec` containing the compressed data. -/// - `buffer_size`: The buffer size to use for the buffered reader. -/// -/// # Returns -/// A `Vec` containing the decompressed data, or an empty `Vec` in case of error. -pub fn decode(data: &Vec, buffer_size: usize) -> Vec { - let decoder: DeflateDecoder<&[u8]> = DeflateDecoder::new(data.as_slice()); - let mut buffered_reader: BufReader> = - BufReader::with_capacity(buffer_size, decoder); - let mut decompressed_data: Vec = Vec::new(); - match buffered_reader.read_to_end(&mut decompressed_data) { - Ok(_) => decompressed_data, - _ => Vec::new(), - } -} diff --git a/src/compress/deflate/mod.rs b/src/compress/deflate/mod.rs deleted file mode 100644 index 5ac80bb..0000000 --- a/src/compress/deflate/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod decode; diff --git a/src/compress/gzip/decode.rs b/src/compress/gzip/decode.rs deleted file mode 100644 index ea90213..0000000 --- a/src/compress/gzip/decode.rs +++ /dev/null @@ -1,28 +0,0 @@ -use flate2::read::GzDecoder; -use std::io::BufReader; -use std::io::Read; - -/// Decodes Gzip compressed data. -/// -/// This function takes a Gzip compressed byte vector and decompresses it using the -/// `flate2` crate's `GzDecoder`. It buffers the decompressed data and returns the -/// result as a vector of bytes. -/// -/// # Arguments -/// - `data` - A reference to a `Vec` containing the compressed Gzip data. -/// - `buffer_size` - The buffer size to use for reading the compressed data. A larger -/// buffer size can improve performance for larger datasets. -/// -/// # Returns -/// - `Vec` - The decompressed data as a vector of bytes. If decompression fails, -/// an empty `Vec` is returned. -pub fn decode(data: &Vec, buffer_size: usize) -> Vec { - let decoder: GzDecoder<&[u8]> = GzDecoder::new(data.as_slice()); - let mut buffered_reader: BufReader> = - BufReader::with_capacity(buffer_size, decoder); - let mut decompressed_data: Vec = Vec::new(); - match buffered_reader.read_to_end(&mut decompressed_data) { - Ok(_) => decompressed_data, - _ => Vec::new(), - } -} diff --git a/src/compress/gzip/mod.rs b/src/compress/gzip/mod.rs deleted file mode 100644 index 5ac80bb..0000000 --- a/src/compress/gzip/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod decode; diff --git a/src/compress/impl.rs b/src/compress/impl.rs deleted file mode 100644 index f54c171..0000000 --- a/src/compress/impl.rs +++ /dev/null @@ -1,73 +0,0 @@ -use std::str::FromStr; - -use super::{ - brotli, - constant::{BR, DEFLATE, GZIP}, - deflate, gzip, - r#type::Compress, -}; -use crate::{request::constant::CONTENT_ENCODING, response::response_header::r#type::Header}; - -impl Default for Compress { - fn default() -> Self { - Self::Unknown - } -} - -impl FromStr for Compress { - type Err = (); - - fn from_str(data: &str) -> Result { - match data.to_lowercase().as_str() { - _data if _data == GZIP => Ok(Self::Gzip), - _data if _data == DEFLATE => Ok(Self::Deflate), - _data if _data == BR => Ok(Self::Br), - _ => Ok(Self::Unknown), - } - } -} - -impl Compress { - /// Extracts the compression type from an HTTP header. - /// - /// This function looks for the `Content-Encoding` header in the provided `Header` and attempts - /// to parse it into a `Compress` enum value. - /// - /// # Arguments - /// - `header` - The HTTP header from which the compression type is to be extracted. - /// - /// # Returns - /// - The `Compress` value corresponding to the `Content-Encoding` header, or `Compress::Unknown` - /// if the header does not match any known compression types. - pub fn from(header: &Header) -> Self { - let content_encoding_key: String = CONTENT_ENCODING.to_lowercase(); - let mut compress: Compress = Self::default(); - for (key, value) in header { - if key.to_lowercase() == content_encoding_key { - compress = value.parse::().unwrap_or_default(); - break; - } - } - compress - } - - /// Decodes data based on the compression type. - /// - /// This function decodes the compressed data using the corresponding compression algorithm - /// (Gzip, Deflate, or Brotli) depending on the `Compress` enum value. - /// - /// # Arguments - /// - `data` - A vector of bytes containing the compressed data. - /// - `buffer_size` - The buffer size to use during decompression. - /// - /// # Returns - /// - A `Vec` containing the decompressed data. - pub fn decode(&self, data: &Vec, buffer_size: usize) -> Vec { - match self { - Self::Gzip => gzip::decode::decode(data, buffer_size), - Self::Deflate => deflate::decode::decode(data, buffer_size), - Self::Br => brotli::decode::decode(data, buffer_size), - Self::Unknown => data.clone(), - } - } -} diff --git a/src/compress/mod.rs b/src/compress/mod.rs deleted file mode 100644 index 2a13138..0000000 --- a/src/compress/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod brotli; -pub mod constant; -pub mod deflate; -pub mod gzip; -pub mod r#impl; -pub mod r#type; diff --git a/src/compress/type.rs b/src/compress/type.rs deleted file mode 100644 index ccf71dd..0000000 --- a/src/compress/type.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -pub enum Compress { - Gzip, - Deflate, - Br, - Unknown, -} diff --git a/src/constant/common.rs b/src/constant/common.rs deleted file mode 100644 index de2f3fd..0000000 --- a/src/constant/common.rs +++ /dev/null @@ -1,50 +0,0 @@ -/// The name of the application. -/// -/// This constant represents the name of the application used for -/// identifying the current application context. -pub static APP_NAME: &str = "http-request"; - -/// A single space character. -/// -/// This constant is used to represent a space character in string -/// or byte operations. -pub static SPACE: &str = " "; - -/// The byte representation of a single space character. -/// -/// This constant provides the byte equivalent of the space character -/// for use in low-level operations. -pub static SPACE_U8: u8 = SPACE.as_bytes()[0]; - -/// A tab character. -/// -/// This constant is used to represent a tab character in string -/// or byte operations. -pub static TAB: &str = "\t"; - -/// The byte representation of a tab character. -/// -/// This constant provides the byte equivalent of the tab character -/// for use in low-level operations. -pub static TAB_U8: u8 = TAB.as_bytes()[0]; - -/// A line break character (newline). -/// -/// This constant is used to represent a line break character in -/// string or byte operations. -pub static BR: &str = "\n"; - -/// A static byte slice representation of the string `BR`. -pub static BR_BYTES: &[u8] = BR.as_bytes(); - -/// A colon followed by a space (`: `). -/// -/// This constant is commonly used in formatted strings, such as -/// headers or key-value pairs, where a colon and a space are needed. -pub static COLON_SPACE: &str = ": "; - -/// The byte representation of the first character in the `COLON_SPACE`. -/// -/// This constant provides the byte equivalent of the colon character -/// from the `COLON_SPACE` string. -pub static COLON_SPACE_BYTES: &[u8] = COLON_SPACE.as_bytes(); diff --git a/src/constant/mod.rs b/src/constant/mod.rs index 702ece4..6e146ba 100644 --- a/src/constant/mod.rs +++ b/src/constant/mod.rs @@ -1,2 +1 @@ -pub mod common; -pub mod request; +pub mod r#type; diff --git a/src/constant/request.rs b/src/constant/type.rs similarity index 57% rename from src/constant/request.rs rename to src/constant/type.rs index 521d5dd..75fa916 100644 --- a/src/constant/request.rs +++ b/src/constant/type.rs @@ -1,3 +1,9 @@ +/// The name of the application. +/// +/// This constant represents the name of the application used for +/// identifying the current application context. +pub static APP_NAME: &str = "http-request"; + /// The default timeout value for HTTP requests, represented in milliseconds. /// This value is used when no specific timeout is provided, ensuring that requests /// have a reasonable maximum duration before timing out. diff --git a/src/content_type/impl.rs b/src/content_type/impl.rs deleted file mode 100644 index 0fecb6c..0000000 --- a/src/content_type/impl.rs +++ /dev/null @@ -1,155 +0,0 @@ -use super::r#type::ContentType; -use crate::request::constant::{ - APPLICATION_JSON, APPLICATION_XML, FORM_URLENCODED, TEXT_HTML, TEXT_PLAIN, -}; -use serde::Serialize; -use serde_json; -use serde_xml_rs; -use std::fmt::{Debug, Display}; -use std::str::FromStr; - -impl ContentType { - /// Handles the `application/json` Content-Type by serializing the provided data - /// into a JSON string. - /// - /// # Type Parameters - /// - `T`: The type of the data to be serialized, which must implement `Serialize`. - /// - /// # Parameters - /// - `data`: The data to be serialized into JSON. - /// - /// # Returns - /// A string containing the serialized JSON representation of the provided data. - /// If serialization fails, it returns an empty JSON object (`{}`). - fn get_application_json(data: &T) -> String { - serde_json::to_string(data).unwrap_or_else(|_| String::from("{}")) - } - - /// Handles the `application/xml` Content-Type by serializing the provided data - /// into an XML string. - /// - /// # Type Parameters - /// - `T`: The type of the data to be serialized, which must implement `Serialize`. - /// - /// # Parameters - /// - `data`: The data to be serialized into XML. - /// - /// # Returns - /// A string containing the serialized XML representation of the provided data. - /// If serialization fails, it returns an empty XML root element (``). - fn get_application_xml(data: &T) -> String { - serde_xml_rs::to_string(data).unwrap_or_else(|_| String::from("")) - } - - /// Handles the `text/plain` Content-Type by formatting the provided data - /// into a plain text string. - /// - /// # Type Parameters - /// - `T`: The type of the data to be formatted, which must implement `Serialize`, `Debug`, `Clone`, and `Default`. - /// - /// # Parameters - /// - `data`: The data to be formatted into plain text. - /// - /// # Returns - /// A plain text string representing the provided data, formatted with the `Debug` trait. - fn get_text_plain(data: &T) -> String { - data.to_string() - } - - /// Handles the `text/html` Content-Type by formatting the provided data - /// into an HTML string, typically inside a simple table. - /// - /// # Type Parameters - /// - `T`: The type of the data to be formatted, which must implement `Serialize`, `Debug`, `Clone`, and `Default`. - /// - /// # Parameters - /// - `data`: The data to be formatted into HTML. - /// - /// # Returns - /// A string containing the HTML representation of the provided data, inside a table row. - fn get_text_html(data: &T) -> String { - let mut html: String = String::from(""); - html.push_str(&format!("", data)); - html.push_str("
{:?}
"); - html - } - - /// Handles the `application/x-www-form-urlencoded` Content-Type by serializing - /// the provided data into a URL-encoded string. - /// - /// # Type Parameters - /// - `T`: The type of the data to be serialized, which must implement `Serialize`. - /// - /// # Parameters - /// - `data`: The data to be serialized into URL-encoded format. - /// - /// # Returns - /// A string containing the URL-encoded representation of the provided data. - /// If serialization fails, it returns an empty string. - fn get_form_url_encoded(data: &T) -> String { - serde_urlencoded::to_string(data).unwrap_or_else(|_| String::from("")) - } - - /// Handles binary data when the `Content-Type` is unknown by formatting the - /// provided data as a hexadecimal string. - /// - /// # Type Parameters - /// - `T`: The type of the data to be formatted, which must implement `Serialize`, `Debug`, `Clone`, and `Default`. - /// - /// # Parameters - /// - `data`: The data to be formatted into binary representation. - /// - /// # Returns - /// A string containing the hexadecimal encoding of the provided data. - fn get_binary(data: &T) -> String { - hex::encode(data.to_string()) - } - - /// Public interface for getting a formatted body string based on the `ContentType`. - /// - /// This method routes the data to the appropriate handler method based on the - /// `ContentType`, formatting the body accordingly. - /// - /// # Type Parameters - /// - `T`: The type of the data to be formatted, which must implement `Serialize`, `Debug`, `Clone`, and `Default`. - /// - /// # Parameters - /// - `data`: The data to be formatted into the body string. - /// - /// # Returns - /// A string containing the formatted body based on the content type, such as JSON, XML, plain text, HTML, etc. - pub fn get_body_string( - &self, - data: &T, - ) -> String { - match self { - Self::ApplicationJson => Self::get_application_json(data), - Self::ApplicationXml => Self::get_application_xml(data), - Self::TextPlain => Self::get_text_plain(data), - Self::TextHtml => Self::get_text_html(data), - Self::FormUrlEncoded => Self::get_form_url_encoded(data), - Self::Unknown => Self::get_binary(data), - } - } -} - -impl FromStr for ContentType { - type Err = (); - - fn from_str(data: &str) -> Result { - match data.to_lowercase().as_str() { - _data if _data == APPLICATION_JSON => Ok(Self::ApplicationJson), - _data if _data == APPLICATION_XML => Ok(Self::ApplicationXml), - _data if _data == TEXT_PLAIN => Ok(Self::TextPlain), - _data if _data == TEXT_HTML => Ok(Self::TextHtml), - _data if _data == FORM_URLENCODED => Ok(Self::FormUrlEncoded), - _ => Ok(Self::Unknown), - } - } -} - -impl Default for ContentType { - fn default() -> Self { - Self::Unknown - } -} diff --git a/src/content_type/mod.rs b/src/content_type/mod.rs deleted file mode 100644 index 6297e83..0000000 --- a/src/content_type/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod r#impl; -pub mod r#type; diff --git a/src/content_type/type.rs b/src/content_type/type.rs deleted file mode 100644 index da1182c..0000000 --- a/src/content_type/type.rs +++ /dev/null @@ -1,22 +0,0 @@ -/// Represents different types of HTTP content types, such as JSON, XML, plain text, HTML, -/// form URL encoded, and an unknown type. -#[derive(Debug, PartialEq, Eq)] -pub enum ContentType { - /// Represents the `application/json` content type. - ApplicationJson, - - /// Represents the `application/xml` content type. - ApplicationXml, - - /// Represents the `text/plain` content type. - TextPlain, - - /// Represents the `text/html` content type. - TextHtml, - - /// Represents the `application/x-www-form-urlencoded` content type. - FormUrlEncoded, - - /// Represents an unknown or unrecognized content type. - Unknown, -} diff --git a/src/http_url/impl.rs b/src/http_url/impl.rs deleted file mode 100644 index 49f3431..0000000 --- a/src/http_url/impl.rs +++ /dev/null @@ -1,47 +0,0 @@ -use super::r#type::HttpUrl; -use crate::{protocol::r#type::Protocol, request::error::r#type::Error}; -use url::Url as UrlParser; - -impl Default for HttpUrl { - fn default() -> Self { - HttpUrl { - protocol: Protocol::Unknown(String::new()), - host: None, - port: None, - path: None, - query: None, - fragment: None, - } - } -} - -impl HttpUrl { - /// Parses a URL string into a `HttpUrl` instance. - /// - /// This method attempts to parse a given URL string into its components such as - /// scheme, username, password, host, port, path, query, and fragment. If the URL - /// is invalid, it returns an `Error::InvalidUrl` error. - /// - /// # Parameters - /// - `url_str`: A string slice representing the URL to be parsed. - /// - /// # Returns - /// Returns a `Result` containing either a `HttpUrl` instance populated with the - /// parsed components or an `Error::InvalidUrl` if the parsing fails. - pub fn parse(url_str: &str) -> Result { - let parsed_url: UrlParser = UrlParser::parse(url_str).map_err(|_| Error::InvalidUrl)?; - let res: Self = Self { - protocol: parsed_url - .scheme() - .to_string() - .parse::() - .unwrap_or_default(), - host: parsed_url.host_str().map(|h| h.to_string()), - port: parsed_url.port(), - path: Some(parsed_url.path().to_string()), - query: parsed_url.query().map(|q| q.to_string()), - fragment: parsed_url.fragment().map(|f| f.to_string()), - }; - Ok(res) - } -} diff --git a/src/http_url/mod.rs b/src/http_url/mod.rs deleted file mode 100644 index 6297e83..0000000 --- a/src/http_url/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod r#impl; -pub mod r#type; diff --git a/src/http_url/type.rs b/src/http_url/type.rs deleted file mode 100644 index 2dd04f2..0000000 --- a/src/http_url/type.rs +++ /dev/null @@ -1,27 +0,0 @@ -use crate::protocol::r#type::Protocol; - -/// A struct representing a parsed URL with various components. -/// -/// This struct is used to store the different components of a URL, such as the scheme, -/// username, password, host, port, path, query, and fragment. It allows for easy -/// handling and manipulation of URL data. -/// -/// # Fields -/// - `scheme`: The URL scheme (e.g., "http", "https") as a string, or `None` if not specified. -/// - `host`: The host portion of the URL (e.g., "example.com"), or `None` if not specified. -/// - `port`: The port number, if specified, or `None` if not specified. -/// - `path`: The path portion of the URL (e.g., "/path/to/resource"), or `None` if not specified. -/// - `query`: The query string, if present, or `None` if not specified. -/// - `fragment`: The fragment identifier, if present, or `None` if not specified. -/// -/// This struct is primarily used for holding the components of a URL after parsing, allowing -/// for easy manipulation and access to the individual components. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct HttpUrl { - pub protocol: Protocol, - pub host: Option, - pub port: Option, - pub path: Option, - pub query: Option, - pub fragment: Option, -} diff --git a/src/http_version/impl.rs b/src/http_version/impl.rs deleted file mode 100644 index b1b309b..0000000 --- a/src/http_version/impl.rs +++ /dev/null @@ -1,20 +0,0 @@ -use super::r#type::HttpVersion; -use crate::request::constant::{HTTP_VERSION_1_1, HTTP_VERSION_2, UNKNOWN_HTTP_VERSION}; -use std::fmt::{self, Display}; - -impl Default for HttpVersion { - fn default() -> Self { - Self::HTTP1_1 - } -} - -impl Display for HttpVersion { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let version_str = match self { - Self::HTTP1_1 => HTTP_VERSION_1_1, - Self::HTTP2 => HTTP_VERSION_2, - Self::Unknown(_) => UNKNOWN_HTTP_VERSION, - }; - write!(f, "{}", version_str) - } -} diff --git a/src/http_version/mod.rs b/src/http_version/mod.rs deleted file mode 100644 index 6297e83..0000000 --- a/src/http_version/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod r#impl; -pub mod r#type; diff --git a/src/http_version/type.rs b/src/http_version/type.rs deleted file mode 100644 index 0c4fa1f..0000000 --- a/src/http_version/type.rs +++ /dev/null @@ -1,20 +0,0 @@ -/// Represents the HTTP version used in the request or response. -/// -/// This enum is used to specify the HTTP version for HTTP requests and responses. -/// It supports the two most common HTTP versions: HTTP/1.1 and HTTP/2. The `HttpVersion` -/// enum allows for easy comparison, cloning, and debugging of the HTTP version. -/// -/// The variants include: -/// - `HTTP1_1`: Represents HTTP version 1.1. -/// - `HTTP2`: Represents HTTP version 2.0. -#[derive(Debug, PartialEq, Clone, Eq)] -pub enum HttpVersion { - /// HTTP version 1.1 - HTTP1_1, - - /// HTTP version 2.0 - HTTP2, - - /// Unknown version - Unknown(String), -} diff --git a/src/lib.rs b/src/lib.rs index 00911d3..ded0bf7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,17 +1,10 @@ pub(crate) mod body; #[cfg(test)] mod cfg; -pub(crate) mod compress; pub(crate) mod constant; -pub(crate) mod content_type; pub(crate) mod global_trait; -pub(crate) mod http_url; -pub(crate) mod http_version; -pub(crate) mod methods; -pub(crate) mod protocol; pub(crate) mod request; pub(crate) mod response; -pub(crate) mod status_code; pub(crate) mod utils; pub use request::{ diff --git a/src/methods/constant.rs b/src/methods/constant.rs deleted file mode 100644 index 15c09c9..0000000 --- a/src/methods/constant.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub static GET: &str = "GET"; -pub static POST: &str = "POST"; diff --git a/src/methods/impl.rs b/src/methods/impl.rs deleted file mode 100644 index 8927770..0000000 --- a/src/methods/impl.rs +++ /dev/null @@ -1,43 +0,0 @@ -use super::r#type::Methods; -use crate::methods::constant::{GET, POST}; -use std::fmt::{self, Display}; - -impl Default for Methods { - fn default() -> Self { - Self::GET - } -} - -/// Provides utility methods for the `Methods` type. -impl Methods { - /// Creates a new instance of `Methods` with the default value of `Self::GET`. - /// - /// This is a shorthand for using the `default` method. - pub fn new() -> Self { - Self::default() - } - - /// Checks if the current method is `GET`. - /// - /// Returns `true` if the method is `GET`, otherwise returns `false`. - pub fn is_get(&self) -> bool { - self.to_owned() == Self::GET.to_owned() - } - - /// Checks if the current method is `POST`. - /// - /// Returns `true` if the method is `POST`, otherwise returns `false`. - pub fn is_post(&self) -> bool { - self.to_owned() == Self::POST.to_owned() - } -} - -impl Display for Methods { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let res: &str = match self { - Self::GET => GET, - Self::POST => POST, - }; - write!(f, "{}", res) - } -} diff --git a/src/methods/mod.rs b/src/methods/mod.rs deleted file mode 100644 index 5c7188f..0000000 --- a/src/methods/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod constant; -pub mod r#impl; -pub mod r#type; diff --git a/src/methods/type.rs b/src/methods/type.rs deleted file mode 100644 index 2dbed0c..0000000 --- a/src/methods/type.rs +++ /dev/null @@ -1,10 +0,0 @@ -/// Defines the `Methods` enum, representing HTTP request methods. -/// -/// The `Methods` enum includes commonly used HTTP methods such as `GET` and `POST`. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Methods { - /// Represents the HTTP `GET` method. - GET, - /// Represents the HTTP `POST` method. - POST, -} diff --git a/src/protocol/impl.rs b/src/protocol/impl.rs deleted file mode 100644 index a8a0478..0000000 --- a/src/protocol/impl.rs +++ /dev/null @@ -1,75 +0,0 @@ -use super::r#type::Protocol; -use crate::request::constant::{HTTP, HTTPS}; -use std::{ - fmt::{self, Display}, - str::FromStr, -}; - -impl Default for Protocol { - fn default() -> Self { - Self::HTTP - } -} - -/// Provides utility methods for the `Protocol` type. -impl Protocol { - /// Creates a new instance of `Protocol` with the default value of `Self::HTTP`. - /// - /// This is a shorthand for using the `default` method. - #[allow(dead_code)] - pub fn new() -> Self { - Self::default() - } - - /// Checks if the current protocol is `HTTP`. - /// - /// Returns `true` if the protocol is `HTTP`, otherwise returns `false`. - #[allow(dead_code)] - pub fn is_http(&self) -> bool { - self.to_owned() == Self::HTTP.to_owned() - } - - /// Checks if the current protocol is `HTTPS`. - /// - /// Returns `true` if the protocol is `HTTPS`, otherwise returns `false`. - pub fn is_https(&self) -> bool { - self.to_owned() == Self::HTTPS.to_owned() - } - - /// Returns the default port associated with the protocol. - /// - /// - Returns `80` for `Self::HTTP`. - /// - Returns `443` for `Self::HTTPS`. - pub fn get_port(&self) -> u16 { - match self { - Self::HTTP => 80, - Self::HTTPS => 443, - Self::Unknown(_) => 80, - } - } -} - -impl Display for Protocol { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let http: String = HTTP.to_lowercase(); - let https: String = HTTPS.to_lowercase(); - let res: &str = match self { - Self::HTTP => http.as_str(), - Self::HTTPS => https.as_str(), - Self::Unknown(protocol) => protocol, - }; - write!(f, "{}", res) - } -} - -impl FromStr for Protocol { - type Err = &'static str; - - fn from_str(data: &str) -> Result { - match data.to_lowercase().as_str() { - _data if _data == HTTP.to_lowercase() => Ok(Self::HTTP), - _data if _data == HTTPS.to_lowercase() => Ok(Self::HTTPS), - _ => Ok(Self::Unknown(data.to_string())), - } - } -} diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs deleted file mode 100644 index 6297e83..0000000 --- a/src/protocol/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod r#impl; -pub mod r#type; diff --git a/src/protocol/type.rs b/src/protocol/type.rs deleted file mode 100644 index d70625d..0000000 --- a/src/protocol/type.rs +++ /dev/null @@ -1,14 +0,0 @@ -/// Defines the `Protocol` enum, representing HTTP-related protocols. -/// -/// The `Protocol` enum includes: -/// - `HTTP`: Represents the HTTP protocol. -/// - `HTTPS`: Represents the HTTPS protocol. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Protocol { - /// Represents the HTTP protocol. - HTTP, - /// Represents the HTTPS protocol. - HTTPS, - /// Unknown - Unknown(String), -} diff --git a/src/request/config/impl.rs b/src/request/config/impl.rs index c31f13b..59a7956 100644 --- a/src/request/config/impl.rs +++ b/src/request/config/impl.rs @@ -1,14 +1,12 @@ use super::r#type::Config; -use crate::{ - constant::request::DEFAULT_TIMEOUT, http_url::r#type::HttpUrl, - http_version::r#type::HttpVersion, -}; +use crate::constant::r#type::DEFAULT_TIMEOUT; +use http_type::*; impl Default for Config { fn default() -> Self { Self { timeout: DEFAULT_TIMEOUT, - url_obj: HttpUrl::default(), + url_obj: HttpUrlComponents::default(), redirect: false, max_redirect_times: 8, redirect_times: 0, diff --git a/src/request/config/type.rs b/src/request/config/type.rs index 4375f74..51c067a 100644 --- a/src/request/config/type.rs +++ b/src/request/config/type.rs @@ -1,4 +1,4 @@ -use crate::{http_url::r#type::HttpUrl, http_version::r#type::HttpVersion}; +use http_type::*; /// Configuration for HTTP requests. /// @@ -12,7 +12,7 @@ use crate::{http_url::r#type::HttpUrl, http_version::r#type::HttpVersion}; /// Requests exceeding this duration will be terminated. /// /// - `url_obj` - The parsed URL object containing the details of the request destination. -/// This field represents the URL that the request will be sent to, parsed into a `HttpUrl` object. +/// This field represents the URL that the request will be sent to, parsed into a `HttpUrlComponents` object. /// /// - `redirect` - A flag indicating whether redirection is enabled for the request. /// If `true`, the client will follow HTTP redirections (e.g., 3xx status codes). @@ -51,7 +51,7 @@ pub struct Config { pub timeout: u64, /// The parsed URL object containing the details of the request destination. - pub url_obj: HttpUrl, + pub url_obj: HttpUrlComponents, /// A flag indicating whether redirection is enabled for the request. pub redirect: bool, diff --git a/src/request/constant.rs b/src/request/constant.rs deleted file mode 100644 index ff3d460..0000000 --- a/src/request/constant.rs +++ /dev/null @@ -1,76 +0,0 @@ -/// A carriage return and newline character sequence (`\r\n`), used to separate lines in HTTP headers. -pub static HTTP_BR: &str = "\r\n"; - -/// A static reference to a byte slice representing the HTTP line break (`\r\n`). -pub static HTTP_BR_BYTES: &[u8] = HTTP_BR.as_bytes(); - -/// A double carriage return and newline character sequence (`\r\n\r\n`), used to separate HTTP headers from the body. -pub static HTTP_DOUBLE_BR: &str = "\r\n\r\n"; - -/// A static reference to a byte slice representing the HTTP double line break (`\r\n\r\n`). -pub static HTTP_DOUBLE_BR_BYTES: &[u8] = HTTP_DOUBLE_BR.as_bytes(); - -/// The HTTP header field name `Location`, used to specify the URL to redirect a client. -pub static LOCATION: &str = "Location"; - -/// The HTTP header field name `Content-Length`, used to specify the length of the response body in bytes. -pub static CONTENT_LENGTH: &str = "Content-Length"; - -/// The HTTP header field name `Content-Type`, used to specify the media type of the resource or the data being sent in an HTTP request or response. -pub static CONTENT_TYPE: &str = "Content-Type"; - -/// The HTTP header name used to indicate the content encoding of the response. -pub static CONTENT_ENCODING: &str = "Content-Encoding"; - -/// The HTTP header field "Accept". -pub static ACCEPT: &str = "Accept"; - -/// The default value for the `Accept` header. -pub static ACCEPT_VALUE: &str = "*/*"; - -/// The HTTP header field "User-Agent". -pub static USER_AGENT: &str = "User-Agent"; - -/// The HTTP header field name `Host`, used to specify the host and port number of the server. -pub static HOST: &str = "Host"; - -/// Unknown HTTP version -pub static UNKNOWN_HTTP_VERSION: &str = ""; - -/// The default HTTP version `HTTP/1.1` used in requests and responses. -pub static HTTP_VERSION_1_1: &str = "HTTP/1.1"; - -/// The default HTTP version `HTTP/2` used in requests and responses. -pub static HTTP_VERSION_2: &str = "HTTP/2"; - -/// The default HTTP path (`/`), typically used in requests when no specific path is provided. -pub static DEFAULT_HTTP_PATH: &str = "/"; - -/// The MIME type for JSON content, typically used for requests and responses -/// containing JSON data. -pub static APPLICATION_JSON: &str = "application/json"; - -/// The MIME type for XML content, typically used for requests and responses -/// containing XML data. -pub static APPLICATION_XML: &str = "application/xml"; - -/// The MIME type for plain text content, typically used for requests and responses -/// containing simple text data. -pub static TEXT_PLAIN: &str = "text/plain"; - -/// The MIME type for HTML content, typically used for requests and responses -/// containing HTML data. -pub static TEXT_HTML: &str = "text/html"; - -/// The MIME type for form-encoded data, commonly used for sending data in the -/// body of HTTP requests, especially for form submissions. -pub static FORM_URLENCODED: &str = "application/x-www-form-urlencoded"; - -/// Query symbols -pub static QUERY_SYMBOL: &str = "?"; - -/// A constant representing the "HTTP" protocol. -pub static HTTP: &str = "HTTP"; - -/// A constant representing the "HTTPS" protocol. -pub static HTTPS: &str = "HTTPS"; diff --git a/src/request/header/mod.rs b/src/request/header/mod.rs deleted file mode 100644 index 6e146ba..0000000 --- a/src/request/header/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod r#type; diff --git a/src/request/header/type.rs b/src/request/header/type.rs deleted file mode 100644 index 491b8cc..0000000 --- a/src/request/header/type.rs +++ /dev/null @@ -1,6 +0,0 @@ -use std::collections::HashMap; - -/// A type alias for a `HashMap`, representing the headers of an HTTP request or response. -/// This structure stores key-value pairs, where each key is the name of an HTTP header (e.g., `Content-Type`, `Host`), -/// and the value is the corresponding header value (e.g., `application/json`, `example.com`). -pub type Header = HashMap<&'static str, &'static str>; diff --git a/src/request/mod.rs b/src/request/mod.rs index eeb5cf9..e53b7db 100644 --- a/src/request/mod.rs +++ b/src/request/mod.rs @@ -1,7 +1,5 @@ pub mod config; -pub mod constant; pub mod error; -pub mod header; pub mod request; pub mod request_builder; pub mod tmp; diff --git a/src/request/request/impl.rs b/src/request/request/impl.rs index 398e032..b7161bc 100644 --- a/src/request/request/impl.rs +++ b/src/request/request/impl.rs @@ -1,21 +1,10 @@ use super::r#type::HttpRequest; +use crate::constant::r#type::APP_NAME; +use crate::global_trait::r#trait::ReadWrite; use crate::{ body::r#type::Body, - constant::common::APP_NAME, - content_type::r#type::ContentType, - http_url::r#type::HttpUrl, - methods::r#type::Methods, - protocol::r#type::Protocol, request::{ - config::r#type::Config, - constant::{ - ACCEPT, ACCEPT_VALUE, CONTENT_TYPE, HTTP_BR, HTTP_BR_BYTES, HTTP_DOUBLE_BR_BYTES, - QUERY_SYMBOL, USER_AGENT, - }, - error::r#type::Error, - header::r#type::Header, - r#trait::Request, - r#type::RequestResult, + config::r#type::Config, error::r#type::Error, r#trait::Request, r#type::RequestResult, tmp::r#type::Tmp, }, response::{ @@ -23,10 +12,8 @@ use crate::{ }, utils::vec::case_insensitive_match, }; -use crate::{ - global_trait::r#trait::ReadWrite, - request::constant::{CONTENT_LENGTH, DEFAULT_HTTP_PATH, HOST, LOCATION}, -}; +use http_constant::*; +use http_type::*; use native_tls::{TlsConnector, TlsStream}; use std::{ collections::HashMap, @@ -59,7 +46,7 @@ impl HttpRequest { } /// Returns the headers of the HTTP request. - fn get_header(&self) -> Header { + fn get_header(&self) -> HttpHeaderSliceMap { self.header.as_ref().clone() } @@ -77,11 +64,11 @@ impl HttpRequest { self.url = Arc::new(url); } - /// Parses the current URL into a `HttpUrl` object. + /// Parses the current URL into a `HttpUrlComponents` object. /// - /// Returns `Ok(HttpUrl)` if the parsing succeeds, or `Err(Error::InvalidUrl)` otherwise. - fn parse_url(&self) -> Result { - if let Ok(parse_res) = HttpUrl::parse(&self.get_url()) { + /// Returns `Ok(HttpUrlComponents)` if the parsing succeeds, or `Err(Error::InvalidUrl)` otherwise. + fn parse_url(&self) -> Result { + if let Ok(parse_res) = HttpUrlComponents::parse(&self.get_url()) { Ok(parse_res) } else { Err(Error::InvalidUrl) diff --git a/src/request/request/type.rs b/src/request/request/type.rs index b3d4a48..fec428b 100644 --- a/src/request/request/type.rs +++ b/src/request/request/type.rs @@ -1,9 +1,9 @@ use crate::{ body::r#type::Body, - methods::r#type::Methods, - request::{config::r#type::Config, header::r#type::Header, tmp::r#type::Tmp}, + request::{config::r#type::Config, tmp::r#type::Tmp}, response::response_binary::r#type::HttpResponseBinary, }; +use http_type::*; use std::sync::Arc; /// Represents an HTTP request, encapsulating various components such as the method, URL, protocol, @@ -17,7 +17,7 @@ pub struct HttpRequest { pub(crate) url: Arc, /// The headers included in the request. - pub(crate) header: Arc
, + pub(crate) header: Arc, /// The type of the body, specifying whether it is text or JSON. pub(crate) body: Arc, diff --git a/src/request/request_builder/impl.rs b/src/request/request_builder/impl.rs index ca9d417..831717b 100644 --- a/src/request/request_builder/impl.rs +++ b/src/request/request_builder/impl.rs @@ -1,10 +1,9 @@ use super::r#type::RequestBuilder; use crate::{ body::r#type::{Body, BodyBinary, BodyJson, BodyText}, - http_version::r#type::HttpVersion, - methods::r#type::Methods, - request::{header::r#type::Header, r#type::BoxHttpRequest, request::r#type::HttpRequest}, + request::{r#type::BoxHttpRequest, request::r#type::HttpRequest}, }; +use http_type::*; use std::sync::Arc; impl Default for RequestBuilder { @@ -112,7 +111,7 @@ impl RequestBuilder { /// /// # Returns /// Returns a mutable reference to the `RequestBuilder` to allow method chaining. - pub fn headers(&mut self, header: Header) -> &mut Self { + pub fn headers(&mut self, header: HttpHeaderSliceMap) -> &mut Self { if let Some(tmp_header) = Arc::get_mut(&mut self.http_request.header) { for (key, value) in header { tmp_header.insert(key, value); diff --git a/src/response/mod.rs b/src/response/mod.rs index 60ca578..dc31b44 100644 --- a/src/response/mod.rs +++ b/src/response/mod.rs @@ -1,5 +1,4 @@ pub mod response_binary; -pub mod response_header; pub mod response_text; pub mod r#trait; pub mod r#type; diff --git a/src/response/response_binary/impl.rs b/src/response/response_binary/impl.rs index 53f3bac..fdfa8ca 100644 --- a/src/response/response_binary/impl.rs +++ b/src/response/response_binary/impl.rs @@ -1,13 +1,11 @@ use super::r#type::HttpResponseBinary; use crate::{ - compress::r#type::Compress, - constant::common::{BR_BYTES, COLON_SPACE_BYTES}, - http_version::r#type::HttpVersion, - request::constant::HTTP_BR_BYTES, response::{r#trait::Response, response_text::r#type::HttpResponseText}, - status_code::r#type::StatusCode, utils::vec::{split_multi_byte, split_whitespace}, }; +use http_compress::Compress; +use http_constant::*; +use http_type::*; use std::{collections::HashMap, vec::IntoIter}; /// Implements the `Response` trait for `HttpResponseBinary`. diff --git a/src/response/response_binary/type.rs b/src/response/response_binary/type.rs index 7857bcc..04af45c 100644 --- a/src/response/response_binary/type.rs +++ b/src/response/response_binary/type.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use http_type::*; /// A struct representing an HTTP response. /// @@ -25,7 +25,7 @@ pub struct HttpResponseBinary { pub status_text: String, /// A `HashMap` of headers, where the key is the header name and the value is the header value. - pub headers: HashMap, + pub headers: HttpHeaderMap, /// The body of the response, which contains the content being returned. pub body: Vec, diff --git a/src/response/response_header/mod.rs b/src/response/response_header/mod.rs deleted file mode 100644 index 6e146ba..0000000 --- a/src/response/response_header/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod r#type; diff --git a/src/response/response_header/type.rs b/src/response/response_header/type.rs deleted file mode 100644 index f84e9d2..0000000 --- a/src/response/response_header/type.rs +++ /dev/null @@ -1,6 +0,0 @@ -use std::collections::HashMap; - -/// A type alias for a `HashMap`, representing the headers of an HTTP request or response. -/// This structure stores key-value pairs, where each key is the name of an HTTP header (e.g., `Content-Type`, `Host`), -/// and the value is the corresponding header value (e.g., `application/json`, `example.com`). -pub type Header = HashMap; diff --git a/src/response/response_text/impl.rs b/src/response/response_text/impl.rs index 9492641..a57ea32 100644 --- a/src/response/response_text/impl.rs +++ b/src/response/response_text/impl.rs @@ -1,10 +1,7 @@ use super::r#type::HttpResponseText; -use crate::{ - compress::r#type::Compress, - http_version::r#type::HttpVersion, - response::{r#trait::Response, response_binary::r#type::HttpResponseBinary}, - status_code::r#type::StatusCode, -}; +use crate::response::{r#trait::Response, response_binary::r#type::HttpResponseBinary}; +use http_compress::Compress; +use http_type::*; use std::collections::HashMap; /// Implements the `Response` trait for `HttpResponseText`. diff --git a/src/response/response_text/type.rs b/src/response/response_text/type.rs index e636397..29ea612 100644 --- a/src/response/response_text/type.rs +++ b/src/response/response_text/type.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use http_type::*; /// A struct representing an HTTP response. /// @@ -25,7 +25,7 @@ pub struct HttpResponseText { pub status_text: String, /// A `HashMap` of headers, where the key is the header name and the value is the header value. - pub headers: HashMap, + pub headers: HttpHeaderMap, /// The body of the response, which contains the content being returned. pub body: String, diff --git a/src/status_code/impl.rs b/src/status_code/impl.rs deleted file mode 100644 index e1f091c..0000000 --- a/src/status_code/impl.rs +++ /dev/null @@ -1,106 +0,0 @@ -use super::r#type::StatusCode; -use std::{ - fmt::{self, Display}, - str::FromStr, -}; - -/// The `StatusCode` enum represents the HTTP status codes. -/// -/// It maps common HTTP status codes to their respective meanings. It provides methods to retrieve -/// the corresponding numeric code as well as the associated status text. Additionally, it implements -/// conversion from a string representation of the status code. -/// -/// # Variants -/// - `Ok`: HTTP status 200, indicating a successful request. -/// - `Created`: HTTP status 201, indicating that the request was successful and resulted in a resource creation. -/// - `NoContent`: HTTP status 204, indicating that the request was successful, but there is no content to return. -/// - `BadRequest`: HTTP status 400, indicating a bad request, often due to incorrect syntax or invalid data. -/// - `Unauthorized`: HTTP status 401, indicating that authentication is required and has failed or not been provided. -/// - `Forbidden`: HTTP status 403, indicating that the server understands the request but refuses to authorize it. -/// - `NotFound`: HTTP status 404, indicating that the requested resource could not be found. -/// - `InternalServerError`: HTTP status 500, indicating that the server encountered an internal error. -/// - `NotImplemented`: HTTP status 501, indicating that the server does not support the functionality required to fulfill the request. -/// - `BadGateway`: HTTP status 502, indicating that the server, while acting as a gateway or proxy, received an invalid response from an upstream server. -/// - `Unknown`: A default variant for unrecognized or undefined status codes. -impl StatusCode { - /// Returns the numeric HTTP status code associated with this status code variant. - /// - /// This method returns the corresponding HTTP numeric status code based on the `StatusCode` variant. - /// For example: - /// - `Self::Ok` returns 200. - /// - `Self::BadRequest` returns 400. - /// - `Self::Unknown` returns 0 (the default for unrecognized status codes). - /// - /// # Parameters - /// - `&self`: A reference to the `StatusCode` enum instance. This represents the specific variant of the `StatusCode` enum that the method is called on. - /// - /// # Return Value - /// - `u16`: The numeric HTTP status code associated with the `StatusCode` variant. For example: - /// - `Self::Ok` returns `200`. - /// - `Self::BadRequest` returns `400`. - /// - `Self::Unknown` returns `0`. - pub fn code(&self) -> u16 { - match self { - Self::Ok => 200, - Self::Created => 201, - Self::NoContent => 204, - Self::BadRequest => 400, - Self::Unauthorized => 401, - Self::Forbidden => 403, - Self::NotFound => 404, - Self::InternalServerError => 500, - Self::NotImplemented => 501, - Self::BadGateway => 502, - Self::Unknown => 0, - } - } - - pub fn same(&self, code_str: &str) -> bool { - self.code().to_string() == code_str || self.to_string() == code_str - } -} - -impl Display for StatusCode { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let res: &str = match self { - Self::Ok => "OK", - Self::Created => "Created", - Self::NoContent => "No Content", - Self::BadRequest => "Bad Request", - Self::Unauthorized => "Unauthorized", - Self::Forbidden => "Forbidden", - Self::NotFound => "Not Found", - Self::InternalServerError => "Internal Server Error", - Self::NotImplemented => "Not Implemented", - Self::BadGateway => "Bad Gateway", - Self::Unknown => "Unknown", - }; - write!(f, "{}", res) - } -} - -impl FromStr for StatusCode { - type Err = (); - - fn from_str(code_str: &str) -> Result { - match code_str { - _code_str if Self::Ok.same(_code_str) => Ok(Self::Ok), - _code_str if Self::Created.same(_code_str) => Ok(Self::Created), - _code_str if Self::NoContent.same(_code_str) => Ok(Self::NoContent), - _code_str if Self::BadRequest.same(_code_str) => Ok(Self::BadRequest), - _code_str if Self::Unauthorized.same(_code_str) => Ok(Self::Unauthorized), - _code_str if Self::Forbidden.same(_code_str) => Ok(Self::Forbidden), - _code_str if Self::NotFound.same(_code_str) => Ok(Self::NotFound), - _code_str if Self::InternalServerError.same(_code_str) => Ok(Self::InternalServerError), - _code_str if Self::NotImplemented.same(_code_str) => Ok(Self::NotImplemented), - _code_str if Self::BadGateway.same(_code_str) => Ok(Self::BadGateway), - _ => Ok(Self::Unknown), - } - } -} - -impl Default for StatusCode { - fn default() -> Self { - Self::Ok - } -} diff --git a/src/status_code/mod.rs b/src/status_code/mod.rs deleted file mode 100644 index 6297e83..0000000 --- a/src/status_code/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod r#impl; -pub mod r#type; diff --git a/src/status_code/type.rs b/src/status_code/type.rs deleted file mode 100644 index b32609b..0000000 --- a/src/status_code/type.rs +++ /dev/null @@ -1,42 +0,0 @@ -/// Enumeration of HTTP status codes representing various HTTP response statuses -/// -/// This enum includes common HTTP status codes that cover successful requests, client errors, -/// and server errors. Each variant represents a specific HTTP status code. -/// -/// # Variants -/// - `Ok`: HTTP 200, indicates that the request was successful and the server has successfully processed it. -/// - `Created`: HTTP 201, indicates that the request was successful and the server has created a new resource. -/// - `NoContent`: HTTP 204, indicates that the request was successful but no content is returned. -/// - `BadRequest`: HTTP 400, indicates that the request is invalid or malformed and the server cannot understand it. -/// - `Unauthorized`: HTTP 401, indicates that the request is unauthorized and requires authentication. -/// - `Forbidden`: HTTP 403, indicates that the server understands the request but refuses to authorize it, usually due to insufficient permissions. -/// - `NotFound`: HTTP 404, indicates that the server cannot find the requested resource. -/// - `InternalServerError`: HTTP 500, indicates that the server encountered an internal error and cannot process the request. -/// - `NotImplemented`: HTTP 501, indicates that the server does not support the functionality required to fulfill the request. -/// - `BadGateway`: HTTP 502, indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server. -/// - `Unknown`: Represents an unknown status code, typically used when the status code is not recognized or is undefined. -/// ``` -pub enum StatusCode { - /// 200 OK - Ok, - /// 201 Created - Created, - /// 204 No Content - NoContent, - /// 400 Bad Request - BadRequest, - /// 401 Unauthorized - Unauthorized, - /// 403 Forbidden - Forbidden, - /// 404 Not Found - NotFound, - /// 500 Internal Server Error - InternalServerError, - /// 501 Not Implemented - NotImplemented, - /// 502 Bad Gateway - BadGateway, - /// Unknown status code - Unknown, -} diff --git a/src/utils/vec.rs b/src/utils/vec.rs index 6d7f941..8be224b 100644 --- a/src/utils/vec.rs +++ b/src/utils/vec.rs @@ -1,4 +1,4 @@ -use crate::constant::common::{SPACE_U8, TAB_U8}; +use http_constant::{SPACE_U8, TAB_U8}; /// Splits a byte slice into parts based on whitespace characters (space or tab). ///