From 94fcb8efdc979e20829ad4408d3ee6c2729cecf2 Mon Sep 17 00:00:00 2001 From: alemi Date: Fri, 25 Oct 2024 17:31:46 +0200 Subject: [PATCH] fix: fallback to plaintext if json parse fails --- src/model/endpoint.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/model/endpoint.rs b/src/model/endpoint.rs index 1451302..70126e9 100644 --- a/src/model/endpoint.rs +++ b/src/model/endpoint.rs @@ -209,16 +209,24 @@ fn replace_recursive(element: toml::Value, env: &toml::Table) -> Result Result { - match res.headers().get("Content-Type") { - None => Ok(res.text().await?), + let content_type = res.headers().get("Content-Type").cloned(); + let raw = res.bytes().await?; + match content_type { + None => Ok(String::from_utf8_lossy(&raw).to_string()), Some(v) => { let content_type = v.to_str()?; if content_type.starts_with("application/json") { - Ok(serde_json::to_string_pretty(&res.json::().await?)?) + match serde_json::from_slice::(&raw) { + Ok(x) => Ok(serde_json::to_string_pretty(&x)?), + Err(e) => { + eprintln!(" ? content-type is 'json' but content is not valid json: {e}"); + Ok(String::from_utf8_lossy(&raw).to_string()) + }, + } } else if content_type.starts_with("text/plain") || content_type.starts_with("text/html") { - Ok(res.text().await?) + Ok(String::from_utf8_lossy(&raw).to_string()) } else { - Ok(format!("base64({})\n", BASE64_STANDARD.encode(res.bytes().await?))) + Ok(format!("base64({})\n", BASE64_STANDARD.encode(raw))) } }, }