Skip to content

Commit

Permalink
feat: use http 1.0.0 for request and response interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
LorenzoLeonardo committed Feb 29, 2024
1 parent 139e065 commit 94b90af
Show file tree
Hide file tree
Showing 19 changed files with 1,325 additions and 501 deletions.
1,054 changes: 968 additions & 86 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ readme = "README.md"
async-curl = "0.3"
curl = "0.4"
derive-deref-rs = "0.1"
http = "0.2"
http = "1.0"
http-types = "2.12.0"
log = "0.4"
thiserror = "1.0"
tokio = { version = "1.36", features = ["rt"] }
Expand Down
16 changes: 7 additions & 9 deletions examples/asynchronous.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use async_curl::actor::CurlActor;
use curl_http_client::{collector::Collector, http_client::HttpClient, request::HttpRequest};
use curl_http_client::{collector::Collector, http_client::HttpClient};
use futures::future;
use http::{HeaderMap, Method};
use url::Url;
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() {
Expand All @@ -16,12 +15,11 @@ async fn main() {

let handle = tokio::spawn(async move {
let collector = Collector::Ram(Vec::new());
let request = HttpRequest {
url: Url::parse("https://www.rust-lang.org/").unwrap(),
method: Method::GET,
headers: HeaderMap::new(),
body: None,
};
let request = Request::builder()
.uri("https://www.rust-lang.org/")
.method(Method::GET)
.body(None)
.unwrap();

let response = HttpClient::new(collector)
.request(request)
Expand Down
15 changes: 6 additions & 9 deletions examples/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,20 @@ use async_curl::actor::CurlActor;
use curl_http_client::{
collector::{Collector, FileInfo},
http_client::HttpClient,
request::HttpRequest,
};
use http::{HeaderMap, Method};
use url::Url;
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() {
let actor = CurlActor::new();

let collector = Collector::File(FileInfo::path(PathBuf::from("<FILE PATH TO SAVE>")));

let request = HttpRequest {
url: Url::parse("<SOURCE URL>").unwrap(),
method: Method::GET,
headers: HeaderMap::new(),
body: None,
};
let request = Request::builder()
.uri("<SOURCE URL>")
.method(Method::GET)
.body(None)
.unwrap();

let response = HttpClient::new(collector)
.request(request)
Expand Down
16 changes: 7 additions & 9 deletions examples/get.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use async_curl::actor::CurlActor;
use curl_http_client::{collector::Collector, http_client::HttpClient, request::HttpRequest};
use http::{HeaderMap, Method};
use url::Url;
use curl_http_client::{collector::Collector, http_client::HttpClient};
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() {
let actor = CurlActor::new();
let collector = Collector::Ram(Vec::new());

let request = HttpRequest {
url: Url::parse("<SOURCE URL>").unwrap(),
method: Method::GET,
headers: HeaderMap::new(),
body: None,
};
let request = Request::builder()
.uri("<SOURCE URL>")
.method(Method::GET)
.body(None)
.unwrap();

let response = HttpClient::new(collector)
.request(request)
Expand Down
16 changes: 7 additions & 9 deletions examples/post.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use async_curl::actor::CurlActor;
use curl_http_client::{collector::Collector, http_client::HttpClient, request::HttpRequest};
use http::{HeaderMap, Method};
use url::Url;
use curl_http_client::{collector::Collector, http_client::HttpClient};
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let actor = CurlActor::new();
let collector = Collector::Ram(Vec::new());

let request = HttpRequest {
url: Url::parse("<TARGET URL>").unwrap(),
method: Method::POST,
headers: HeaderMap::new(),
body: Some("test body".as_bytes().to_vec()),
};
let request = Request::builder()
.uri("<TARGET URL>")
.method(Method::POST)
.body(Some("test body".as_bytes().to_vec()))
.unwrap();

let response = HttpClient::new(collector)
.request(request)
Expand Down
15 changes: 6 additions & 9 deletions examples/resume_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ use async_curl::actor::CurlActor;
use curl_http_client::{
collector::{Collector, FileInfo},
http_client::{BytesOffset, HttpClient},
request::HttpRequest,
};
use http::{HeaderMap, Method};
use url::Url;
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand All @@ -17,12 +15,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let collector = Collector::File(FileInfo::path(save_to.clone()));

let partial_download_file_size = fs::metadata(save_to.as_path())?.len() as usize;
let request = HttpRequest {
url: Url::parse("<SOURCE URL>").unwrap(),
method: Method::GET,
headers: HeaderMap::new(),
body: None,
};
let request = Request::builder()
.uri("<SOURCE URL>")
.method(Method::GET)
.body(None)
.unwrap();

let response = HttpClient::new(collector)
.resume_from(BytesOffset::from(partial_download_file_size))
Expand Down
15 changes: 6 additions & 9 deletions examples/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ use async_curl::actor::CurlActor;
use curl_http_client::{
collector::{Collector, FileInfo},
http_client::{FileSize, HttpClient},
request::HttpRequest,
};
use http::{HeaderMap, Method};
use url::Url;
use http::{Method, Request};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand All @@ -17,12 +15,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let actor = CurlActor::new();
let collector = Collector::File(FileInfo::path(file_to_be_uploaded));

let request = HttpRequest {
url: Url::parse("<TARGET URL>").unwrap(),
method: Method::PUT,
headers: HeaderMap::new(),
body: None,
};
let request = Request::builder()
.uri("<TARGET URL>")
.method(Method::PUT)
.body(None)
.unwrap();

let response = HttpClient::new(collector)
.upload_file_size(FileSize::from(file_size))
Expand Down
64 changes: 33 additions & 31 deletions src/http_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ use curl::easy::{Auth, Easy2, Handler, HttpVersion, ProxyType, SslVersion, TimeC
use derive_deref_rs::Deref;
use http::{
header::{CONTENT_LENGTH, CONTENT_TYPE},
HeaderMap, HeaderValue, Method, StatusCode,
HeaderMap, HeaderValue, Method, Request, Response,
};
use log::trace;

use crate::{
collector::ExtendedHandler, error::Error, request::HttpRequest, response::HttpResponse,
};
use crate::{collector::ExtendedHandler, error::Error};

/// Proceed to building state
pub struct Build;
Expand Down Expand Up @@ -79,14 +77,17 @@ where
///
/// The HttpRequest can be customized by the caller by setting the Url, Method Type,
/// Headers and the Body.
pub fn request(mut self, request: HttpRequest) -> Result<Self, Error<C>> {
self.easy.url(&request.url.to_string()[..]).map_err(|e| {
trace!("{:?}", e);
Error::Curl(e)
})?;
pub fn request(mut self, request: Request<Option<Vec<u8>>>) -> Result<Self, Error<C>> {
self.easy
.url(request.uri().to_string().as_str())
.map_err(|e| {
trace!("{:?}", e);
Error::Curl(e)
})?;

let mut headers = curl::easy::List::new();
request.headers.iter().try_for_each(|(name, value)| {

request.headers().iter().try_for_each(|(name, value)| {
headers
.append(&format!(
"{}: {}",
Expand All @@ -108,15 +109,16 @@ where
Error::Curl(e)
})?;

match request.method {
match *request.method() {
Method::POST => {
self.easy.post(true).map_err(Error::Curl)?;
if let Some(body) = request.body {

if let Some(body) = request.body() {
self.easy.post_field_size(body.len() as u64).map_err(|e| {
trace!("{:?}", e);
Error::Curl(e)
})?;
self.easy.post_fields_copy(body.as_slice()).map_err(|e| {
self.easy.post_fields_copy(body).map_err(|e| {
trace!("{:?}", e);
Error::Curl(e)
})?;
Expand Down Expand Up @@ -827,7 +829,7 @@ where
}

/// This will perform the curl operation asynchronously.
pub async fn perform(self) -> Result<HttpResponse, Error<C>> {
pub async fn perform(self) -> Result<Response<Option<Vec<u8>>>, Error<C>> {
let easy = self.send_request().await?;

let (data, headers) = easy.get_ref().get_response_body_and_headers();
Expand Down Expand Up @@ -875,14 +877,14 @@ where
response_header
};

Ok(HttpResponse {
status_code: StatusCode::from_u16(status_code).map_err(|err| {
trace!("{:?}", err);
Error::Http(err.to_string())
})?,
headers: response_header,
body: data,
})
let mut response = Response::builder();
for (name, value) in &response_header {
response = response.header(name, value);
}

response = response.status(status_code);

response.body(data).map_err(|e| Error::Http(e.to_string()))
}
}

Expand All @@ -903,7 +905,7 @@ where
}

/// This will perform the curl operation synchronously.
pub fn perform(self) -> Result<HttpResponse, Error<C>> {
pub fn perform(self) -> Result<Response<Option<Vec<u8>>>, Error<C>> {
let easy = self.send_request()?;

let (data, headers) = easy.get_ref().get_response_body_and_headers();
Expand Down Expand Up @@ -951,14 +953,14 @@ where
response_header
};

Ok(HttpResponse {
status_code: StatusCode::from_u16(status_code).map_err(|err| {
trace!("{:?}", err);
Error::Http(err.to_string())
})?,
headers: response_header,
body: data,
})
let mut response = Response::builder();
for (name, value) in &response_header {
response = response.header(name, value);
}

response = response.status(status_code);

response.body(data).map_err(|e| Error::Http(e.to_string()))
}
}
/// A strong type unit when setting download speed and upload speed
Expand Down
Loading

0 comments on commit 94b90af

Please sign in to comment.