如何将http :: HeaderMap序列化为JSON? [英] How to serialize http::HeaderMap into JSON?

查看:204
本文介绍了如何将http :: HeaderMap序列化为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序列化HTTP请求标头的正确方法是什么( )转换为Rust中的JSON?

What is the proper way of serializing HTTP request headers (http::HeaderMap) into JSON in Rust?

我正在实现AWS Lambda函数,并且希望有一个简单的echo函数用于调试.

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())
}

是否有一种简单的方法可以将req.headers()转换为JSON并返回?

Is there an easy way to convert req.headers() to JSON and return?

推荐答案

没有适当"的方法.就像没有自动为结构实现Display的正确"方法一样,也没有一种将某些数据序列化为JSON的真实方法.

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.

如果您所需要做的只是获取某事作为JSON,并且由于这是用于调试,我只需打印出标头的调试形式,然后将其转换为 Value :

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()
}

如果您想要一些更结构化的内容,可以(有损失!)将标头转换为HashMap<String, Vec<String>>.这种类型可以简单地序列化为JSON对象:

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
}

这篇关于如何将http :: HeaderMap序列化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆