What is the proper way of serializing HTTP request headers (http::HeaderMap
) into JSON in Rust?
I am implementing an AWS Lambda function and I would like to have a simple echo function for debugging.
use lambda_http::{lambda, IntoResponse, Request};
use lambda_runtime::{error::HandlerError, Context};
use log::{self, info};
use simple_logger;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
simple_logger::init_with_level(log::Level::Debug)?;
info!("Starting up...");
lambda!(handler);
return Ok(());
}
fn handler(req: Request, ctx: Context) -> Result<impl IntoResponse, HandlerError> {
Ok(format!("{}", req.headers()).into_response())
}
Is there an easy way to convert req.headers()
to JSON and return?
There is no "proper" way to do so. Just like there's no "proper" way to automatically implement Display
for a struct, there's no One True Way to serialize some piece of data to JSON.
If all you need is to get something that counts as JSON, and since this is for debugging, I'd just print out the debug form of the headers and then convert it into a Value
:
use http::{header::HeaderValue, HeaderMap}; // 0.1.17
use serde_json; // 1.0.39
fn convert(headers: &HeaderMap<HeaderValue>) -> serde_json::Value {
format!("{:?}", headers).into()
}
If you want something a bit more structured, you can (lossily!) convert the headers to a HashMap<String, Vec<String>>
. This type can be trivially serialized to a JSON object:
use http::{header::HeaderValue, HeaderMap}; // 0.1.17
use std::collections::HashMap;
fn convert(headers: &HeaderMap<HeaderValue>) -> HashMap<String, Vec<String>> {
let mut header_hashmap = HashMap::new();
for (k, v) in headers {
let k = k.as_str().to_owned();
let v = String::from_utf8_lossy(v.as_bytes()).into_owned();
header_hashmap.entry(k).or_insert_with(Vec::new).push(v)
}
header_hashmap
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With