8 个版本 (4 个重大更改)
0.5.0 | 2024年6月24日 |
---|---|
0.4.1 | 2024年4月14日 |
0.3.0 | 2024年2月29日 |
0.2.0 | 2023年12月14日 |
0.1.0 | 2023年11月30日 |
#1236 in Web 编程
86 每月下载量
用于 2 crates
29KB
462 行
axum-serde
📑 概述
axum-serde 是一个库,为 Axum 网络框架提供多个基于 serde 的提取器/响应。它还提供了一个宏,可以轻松自定义提取器和响应,而无需编写大量样板代码。
如果您之前在 axum 0.6 中使用过如 axum-yaml、axum-msgpack 等crate,并希望升级到 axum 0.7,则可以使用 axum-serde 作为替代方案来简化迁移,而无需对现有代码进行太多修改。
🚀 基本用法
- 安装
cargo add axum-serde --features yaml,sonic
# Enable features as you need
- 示例
use axum::routing::post;
use axum::Router;
use axum_serde::{Sonic, Yaml};
use serde::{Deserialize, Serialize};
use std::net::{Ipv4Addr, SocketAddr};
use tokio::net::TcpListener;
#[derive(Deserialize, Serialize)]
pub struct Data {
pub a: i32,
pub b: String,
}
pub async fn yaml_to_json(Yaml(data): Yaml<Data>) -> Sonic<Data> {
Sonic(data)
}
pub async fn json_to_yaml(Sonic(data): Sonic<Data>) -> Yaml<Data> {
Yaml(data)
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let router = Router::new()
.route("/y2j", post(yaml_to_json))
.route("/j2y", post(json_to_yaml));
let listener = TcpListener::bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, 8080))).await?;
axum::serve(listener, router.into_make_service()).await?;
Ok(())
}
- 测试
curl -X POST https://127.0.0.1:8080/y2j -H "Content-Type: application/yaml" -d $'a: 42\nb: Hello'
curl -X POST https://127.0.0.1:8080/j2y -H "Content-Type: application/json" -d '{"a": 42, "b": "Hello, world!"}'
🗂️ 提取器/响应
提取器 | 功能 | 后端 |
---|---|---|
Yaml<T> |
yaml | serde_yaml v0.9.33 |
MsgPack<T> / MsgPackRaw<T> |
msgpack | rmp-serde v1.3.0 |
Toml<T> |
toml | toml v0.8.14 |
Xml<T> |
xml | quick-xml v0.33.0 |
Sonic<T> |
sonic | sonic-rs v0.3.7 |
Cbor<T> |
cbor | ciborium v0.2.2 |
🎁 自定义提取器/响应
使用 extractor
宏以最小化样板代码创建自定义提取器
- 示例
use axum_serde::{
extractor,
macros::{DeserializeOwned, Serialize},
};
extractor!(
MyFormat, // The name of the data format.
MyFmt, // The actual type name of the HTTP extractor/response.
"application/myfmt", // The Content-Type that this extractor supports.
from_slice, // A function identifier for deserializing data from the HTTP request body.
String, // The type of error that can occur when deserializing from the request body.
to_vec, // A function identifier for serializing the HTTP response body to bytes.
myfmt // The test module name.
);
fn from_slice<T: DeserializeOwned>(_bytes: &[u8]) -> Result<T, String> {
todo!()
}
fn to_vec<T: Serialize>(_value: &T) -> Result<Vec<u8>, String> {
todo!()
}
- 测试
运行测试需要更多的 dev-dependencies
# Add dev-dependencies for tests
cargo add axum-test --dev
cargo add serde --features derive --dev
cargo add tokio --features macros --dev
# Run the generated tests
cargo test myfmt
📜 许可证
本项目采用 MIT 许可证。
📚 参考资料
依赖关系
~1.7–9.5MB
~91K SLoC