From b1ab7f433a74fceeadabc32d0442dfeefc8b3f72 Mon Sep 17 00:00:00 2001 From: alemi Date: Sat, 19 Oct 2024 05:28:44 +0200 Subject: [PATCH] feat: format json if content-type json, show body --- Cargo.lock | 1 + Cargo.toml | 1 + src/model.rs | 16 ++++++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a8f937e..3619b4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -813,6 +813,7 @@ checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" name = "postwoman" version = "0.2.0" dependencies = [ + "base64", "chrono", "clap", "http", diff --git a/Cargo.toml b/Cargo.toml index 66eab3e..0d281a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +base64 = "0.22.1" chrono = "0.4" clap = { version = "4.5", features = ["derive"] } http = "1.1.0" diff --git a/src/model.rs b/src/model.rs index c7b276a..8840806 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1,5 +1,6 @@ use std::str::FromStr; +use base64::{prelude::BASE64_STANDARD, Engine}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use crate::APP_USER_AGENT; @@ -151,8 +152,8 @@ impl Endpoint { Ok(match self.extract.unwrap_or_default() { StringOr::Str(_query) => todo!(), StringOr::T(Extractor::Discard) => "".to_string(), - StringOr::T(Extractor::Debug) => format!("{res:#?}\n"), - StringOr::T(Extractor::Body) => res.text().await? + "\n", + StringOr::T(Extractor::Debug) => format!("{res:#?}\nBody: ") + &format_body(res).await? + "\n", // ughhh + StringOr::T(Extractor::Body) => format_body(res).await?, StringOr::T(Extractor::Header { key }) => res .headers() .get(&key) @@ -164,6 +165,17 @@ impl Endpoint { } } +async fn format_body(res: reqwest::Response) -> Result { + match res.headers().get("Content-Type") { + None => Ok(res.text().await? + "\n"), + Some(v) => match v.to_str()? { + "application/json" => Ok(serde_json::to_string_pretty(&res.json::().await?)? + "\n"), + "text/plain" => Ok(res.text().await? + "\n"), + _ => Ok(format!("base64({})\n", BASE64_STANDARD.encode(res.bytes().await?))), + }, + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum StringOr {