Skip to content

Commit

Permalink
Log response body if very verbose option is used.
Browse files Browse the repository at this point in the history
  • Loading branch information
jcamiel authored and fabricereix committed Jun 19, 2022
1 parent 75b34f8 commit 1c81471
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions packages/hurl/src/http/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,11 @@ impl Client {
body,
duration,
};

if self.options.verbosity == Some(Verbosity::VeryVerbose) {
response.log_body();
}

Ok((request, response))
}

Expand Down Expand Up @@ -635,6 +640,47 @@ pub fn decode_header(data: &[u8]) -> Option<String> {
}
}

impl Response {
///
/// Log a response body as text if possible, or a slice of body bytes.
///
/// # Arguments
///
/// * `response` - The HTTP response
fn log_body(&self) {
eprintln!("* Response:");

// We try to decode the HTTP body as text if the response has a text kind content type.
// If it ok, we print each line of the body in debug format. Otherwise, we
// print the body first 64 bytes.
if let Some(content_type) = self.content_type() {
if !content_type.contains("text") {
self.log_bytes(64);
return;
}
}
match self.text() {
Ok(text) => text.split('\n').for_each(|l| eprintln!("* {}", l)),
Err(_) => self.log_bytes(64),
}
}

///
/// Log a response bytes with a maximum size.
///
/// # Arguments
///
/// * `max` - The maximum number if bytes to log
fn log_bytes(&self, max: usize) {
let bytes = if self.body.len() > max {
&self.body[..max]
} else {
&self.body
};
eprintln!("* Bytes <{}...>", hex::encode(bytes))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 1c81471

Please sign in to comment.