Skip to content

Commit

Permalink
feat:7.0.0 struct update�[D�[D�[D�[D�[D�[D�[C�[C�[C�[C�[C�[C�[C�[C�[C…
Browse files Browse the repository at this point in the history
…and add decode response
  • Loading branch information
ltpp-universe committed Dec 3, 2024
1 parent abcf845 commit e9ddabb
Show file tree
Hide file tree
Showing 65 changed files with 784 additions and 634 deletions.
74 changes: 73 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
[package]
name = "http-request"
version = "6.0.2"
version = "7.0.0"
edition = "2021"
authors = ["ltpp-universe <[email protected]>"]
license = "MIT"
description = """http_request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, and automatic handling of redirects (including detecting redirect loops), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects."""
description = """http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects."""
keywords = ["http", "request", "response", "tcp", "redirect"]
repository = "https://github.com/ltpp-universe/http-request.git"

[dependencies]
brotli = "7.0.0"
flate2 = "1.0.35"
hex = "0.4.3"
native-tls = "0.2.12"
serde = { version = "1.0", features = ["derive"] }
Expand Down
23 changes: 14 additions & 9 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@

[Official Documentation](https://docs.ltpp.vip/HTTP-REQUEST/)

> http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, and automatic handling of redirects (including detecting redirect loops), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
[Api Docs](https://docs.rs/http-request/latest/http_request/)

> http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.

## Features

- **Support for HTTP/HTTPS**: Supports both HTTP and HTTPS protocols.
- **Lightweight Design**: The `http_request` crate provides a simple and efficient API for building, sending, and handling HTTP requests while minimizing resource consumption.
- **Supports Common HTTP Methods**: Supports common HTTP methods such as GET and POST.
- **Flexible Request Building**: Offers rich configuration options through `HttpRequestBuilder` to set request headers, bodies, and URLs.
- **Flexible Request Building**: Offers rich configuration options through `RequestBuilder` to set request headers, bodies, and URLs.
- **Simple Error Handling**: Utilizes the `Result` type to handle errors in requests and responses, making error handling straightforward.
- **Custom Headers and Request Bodies**: Easily add custom headers and request bodies.
- **Response Handling**: Provides a simple wrapper around HTTP responses, making it easy to access and process response data.
- **Optimized Memory Management**: Implements efficient memory management to minimize unnecessary memory allocations and improve performance.
- **Redirect Handling**: Supports redirect handling, allows setting the maximum number of redirects, and includes redirect loop detection.
- **timeout**: Supports timeout
- **timeout**: Supports timeout.
- **Automatic and Manual Response Body Decoding**: Supports both automatic and manual decoding of response bodies, allowing for seamless interaction with different content types (e.g., JSON, XML, etc.).

## Installation

Expand All @@ -39,14 +42,15 @@ use http_request::*;
use std::collections::HashMap;
let mut header: HashMap<&str, &str> = HashMap::new();
header.insert("header-key", "header-value");
let mut _request_builder = HttpRequestBuilder::new()
let mut _request_builder = RequestBuilder::new()
.get("https://ltpp.vip/")
.headers(header)
.timeout(6000)
.redirect()
.max_redirect_times(8)
.http1_1_only()
.buffer(4096)
.decode()
.builder();
_request_builder
.send()
Expand All @@ -68,7 +72,7 @@ let mut header: HashMap<&str, &str> = HashMap::new();
header.insert("header-key", "header-value");
let mut body: HashMap<&str, &str> = HashMap::new();
body.insert("body-key", "body-value");
let mut _request_builder = HttpRequestBuilder::new()
let mut _request_builder = RequestBuilder::new()
.post("http://localhost:80")
.json(body)
.headers(header)
Expand All @@ -81,7 +85,7 @@ let mut _request_builder = HttpRequestBuilder::new()
_request_builder
.send()
.and_then(|response| {
println!("{:?}", response.text());
println!("{:?}", response.decode().text());
Ok(())
})
.unwrap_or_else(|e| println!("Error => {}", e));
Expand All @@ -94,7 +98,7 @@ use http_request::*;
use std::collections::HashMap;
let mut header: HashMap<&str, &str> = HashMap::new();
header.insert("header-key", "header-value");
let mut _request_builder = HttpRequestBuilder::new()
let mut _request_builder = RequestBuilder::new()
.post("http://localhost")
.text("hello")
.headers(header)
Expand All @@ -103,6 +107,7 @@ let mut _request_builder = HttpRequestBuilder::new()
.max_redirect_times(8)
.http1_1_only()
.buffer(4096)
.decode()
.builder();
_request_builder
.send()
Expand All @@ -120,7 +125,7 @@ use http_request::*;
use std::collections::HashMap;
let mut header: HashMap<&str, &str> = HashMap::new();
header.insert("header-key", "header-value");
let mut _request_builder = HttpRequestBuilder::new()
let mut _request_builder = RequestBuilder::new()
.post("http://localhost")
.body("hello".as_bytes())
.headers(header)
Expand All @@ -133,7 +138,7 @@ let mut _request_builder = HttpRequestBuilder::new()
_request_builder
.send()
.and_then(|response| {
println!("{:?}", response.text());
println!("{:?}", response.decode(4096).text());
Ok(())
})
.unwrap_or_else(|e| println!("Error => {}", e));
Expand Down
54 changes: 8 additions & 46 deletions src/body/impl.rs
Original file line number Diff line number Diff line change
@@ -1,74 +1,36 @@
use super::r#type::Body;
use serde::{Serialize, Serializer};
use std::fmt::{self};
use std::fmt::{self, Display};

/// Represents the body of a request or response, which can be either plain text, JSON, or binary data.
impl Default for Body {
/// Provides a default implementation for the `Body` enum.
///
/// Returns a `Body::Text` variant with an empty string as the default body.
fn default() -> Self {
Self::Text("")
}
}

/// Implements the `fmt::Display` trait for the `Body` enum.
///
/// This trait is responsible for providing a human-readable representation of the body:
/// - For the `Text` variant, the contained text is displayed.
/// - For the `Json` variant, the JSON is serialized to a string. If serialization fails,
/// an empty JSON object (`{}`) is displayed.
/// - For the `Binary` variant, the binary data is displayed in a debug format.
impl fmt::Display for Body {
/// Formats the `Body` instance for user-friendly display.
///
/// # Parameters
/// - `f`: A mutable reference to the formatter.
///
/// # Returns
/// A `Result` indicating whether the formatting was successful. The result is
/// `fmt::Result` which is either `Ok` or an error.
impl Display for Body {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Body::Text(text) => write!(f, "{}", text.to_string()),
Body::Json(json) => write!(
Self::Text(text) => write!(f, "{}", text.to_string()),
Self::Json(json) => write!(
f,
"{:?}",
serde_json::to_string(json).unwrap_or_else(|_| String::from("{}"))
),
Body::Binary(binary) => write!(f, "{:?}", binary),
Self::Binary(binary) => write!(f, "{:?}", binary),
}
}
}

/// Implements the `Serialize` trait for the `Body` enum.
///
/// This trait enables the serialization of the `Body` enum into different formats using
/// the `serde` framework:
/// - The `Text` variant is serialized as a plain string.
/// - The `Json` variant is serialized using the provided `serde` serializer.
/// - The `Binary` variant is serialized as binary data.
impl Serialize for Body {
/// Serializes the `Body` instance into the given serializer.
///
/// # Type Parameters
/// - `S`: The serializer type implementing the `Serializer` trait.
///
/// # Parameters
/// - `serializer`: The serializer used for serialization, which will handle
/// the transformation of the `Body` into the target format.
///
/// # Returns
/// A `Result` containing either the successfully serialized output or an error.
/// If successful, it returns `S::Ok`; if an error occurs, it returns `S::Error`.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Body::Text(text) => text.serialize(serializer),
Body::Json(json) => json.serialize(serializer),
Body::Binary(binary) => binary.serialize(serializer),
Self::Text(text) => text.serialize(serializer),
Self::Json(json) => json.serialize(serializer),
Self::Binary(binary) => binary.serialize(serializer),
}
}
}
2 changes: 1 addition & 1 deletion src/body/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub type BodyBinary = &'static [u8];
/// Represents the body of an HTTP request, which can be either plain text, JSON, or binary data.
/// This enum allows different types of content to be used in the body of the request, supporting
/// both structured and unstructured data formats.
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Body {
/// The text variant of the body, containing plain string content.
///
Expand Down
Loading

0 comments on commit e9ddabb

Please sign in to comment.