Skip to content

Commit

Permalink
support custom collector handler
Browse files Browse the repository at this point in the history
this allows one to implement any of the curl::easy::Handler
methods that one wish without having to overcomplicate the nice
working out of the box collector provided by your lib
  • Loading branch information
glendc authored and LorenzoLeonardo committed Jan 28, 2024
1 parent 5108160 commit c4cfbbf
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 66 deletions.
12 changes: 10 additions & 2 deletions src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ fn send_transfer_info(info: &FileInfo) {
}
}

/// This is an extended trait for the curl::easy::Handler trait.
pub trait ExtendedHandler: Handler {
// Return the response body if the Collector if available.
fn get_response_body(&self) -> Option<Vec<u8>> {
None
}
}

/// The Collector will handle two types in order to store data, via File or via RAM.
/// Collector::File(FileInfo) is useful to be able to download and upload files.
/// Collector::Ram(`Vec<u8>`) is used to store response body into Memory.
Expand Down Expand Up @@ -188,12 +196,12 @@ impl Handler for Collector {
}
}

impl Collector {
impl ExtendedHandler for Collector {
/// If Collector::File(FileInfo) is set, there will be no response body since the response
/// will be stored into a file.
///
/// If Collector::Ram(`Vec<u8>`) is set, the response body can be obtain here.
pub fn get_response_body(&self) -> Option<Vec<u8>> {
fn get_response_body(&self) -> Option<Vec<u8>> {
match self {
Collector::File(_) => None,
Collector::Ram(container) => Some(container.clone()),
Expand Down
16 changes: 11 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
use std::fmt::Debug;

use crate::collector::Collector;
use crate::collector::ExtendedHandler;

/// Error type returned by failed curl HTTP requests.
#[derive(Debug)]
pub enum Error {
pub enum Error<C>
where
C: ExtendedHandler + Debug + Send + 'static,
{
Curl(curl::Error),
Http(String),
Perform(async_curl::error::Error<Collector>),
Perform(async_curl::error::Error<C>),
Other(String),
}

impl std::fmt::Display for Error {
impl<C> std::fmt::Display for Error<C>
where
C: ExtendedHandler + Debug + Send + 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::Curl(err) => write!(f, "{}", err),
Expand All @@ -22,4 +28,4 @@ impl std::fmt::Display for Error {
}
}

impl std::error::Error for Error {}
impl<C> std::error::Error for Error<C> where C: ExtendedHandler + Debug + Send + 'static {}
Loading

0 comments on commit c4cfbbf

Please sign in to comment.