folk_plugin_http/
payload.rs1use std::collections::HashMap;
6
7use anyhow::{Context, Result};
8use axum::body::Body;
9use bytes::Bytes;
10
11pub async fn encode_request(req: axum::http::Request<Body>) -> Result<serde_json::Value> {
13 let (parts, body) = req.into_parts();
14 let body_bytes = axum::body::to_bytes(body, 10 * 1024 * 1024)
15 .await
16 .context("read request body")?;
17
18 let headers: HashMap<String, String> = parts
19 .headers
20 .iter()
21 .filter_map(|(k, v)| Some((k.to_string(), v.to_str().ok()?.to_string())))
22 .collect();
23
24 Ok(serde_json::json!({
25 "method": parts.method.to_string(),
26 "uri": parts.uri.to_string(),
27 "headers": headers,
28 "body": String::from_utf8_lossy(&body_bytes),
29 }))
30}
31
32pub fn decode_response(value: serde_json::Value) -> Result<axum::http::Response<Body>> {
34 let status = value.get("status").and_then(|v| v.as_u64()).unwrap_or(200) as u16;
35
36 let body = value.get("body").and_then(|v| v.as_str()).unwrap_or("");
37
38 let mut builder = axum::http::Response::builder().status(status);
39
40 if let Some(headers) = value.get("headers").and_then(|v| v.as_object()) {
41 for (k, v) in headers {
42 if let Some(v_str) = v.as_str() {
43 builder = builder.header(k.as_str(), v_str);
44 }
45 }
46 }
47
48 builder
49 .body(Body::from(Bytes::from(body.to_string())))
50 .context("build response")
51}