6

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?

fedonev
  • 20,327
  • 2
  • 25
  • 34
Istvan
  • 7,500
  • 9
  • 59
  • 109
  • 1
    So you do not care *whatsoever* what the format of the returned JSON is? Just so long as it's something that counts as JSON? – Shepmaster Apr 12 '19 at 14:35

1 Answers1

8

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
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366