How to serialize http::HeaderMap into JSON?

柔情痞子 提交于 2020-05-29 06:41:33

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/55653917/how-to-serialize-httpheadermap-into-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!