7 个版本 (破坏性更新)

0.6.0 2024年1月10日
0.5.1 2023年10月26日
0.4.0 2023年10月26日
0.3.0 2023年10月10日
0.1.0 2023年10月8日

#1636 in 网页编程

Download history 118/week @ 2024-04-20 186/week @ 2024-04-27 182/week @ 2024-05-04 27/week @ 2024-05-11 44/week @ 2024-05-18 115/week @ 2024-05-25 131/week @ 2024-06-01 106/week @ 2024-06-08 341/week @ 2024-06-15 437/week @ 2024-06-22 227/week @ 2024-06-29 480/week @ 2024-07-06 362/week @ 2024-07-13 379/week @ 2024-07-20 423/week @ 2024-07-27 510/week @ 2024-08-03

每月下载 1,693

MIT/Apache

47KB
731

problem_details

Maintenance

RFC 9457 / RFC 7807 HTTP API 问题详情。

该包提供了 ProblemDetails 结构体,它实现了 RFC 9457 / RFC 7807 问题详情规范。

它支持使用 JSON 序列化和反序列化问题详情,并提供与 axum (0.7)poem (2.0) 网页框架的集成。

用法

以下示例展示了如何创建一个问题详情对象,该对象生成 RFC 中的示例 JSON

use http::Uri;
use problem_details::ProblemDetails;

#[derive(serde::Serialize)]
struct OutOfCreditExt {
   balance: u32,
   accounts: Vec<String>,
}

let details = ProblemDetails::new()
    .with_type(Uri::from_static("https://example.com/probs/out-of-credit"))
    .with_title("You do not have enough credit.")
    .with_detail("Your current balance is 30, but that costs 50.")
    .with_instance(Uri::from_static("/account/12345/msgs/abc"))
    .with_extensions(OutOfCreditExt {
        balance: 30,
        accounts: vec![
            "/account/12345".to_string(),
            "/account/67890".to_string(),
        ],
    });

let json = serde_json::to_value(&details).unwrap();

assert_eq!(json, serde_json::json!({
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc",
  "balance": 30,
  "accounts": [
    "/account/12345",
    "/account/67890"
  ]
}));

扩展

扩展 可以使用 with_extensions 方法添加到问题详情对象中。扩展通过定义扩展字段的结构体传递。

在序列化期间,扩展字段被扁平化到问题详情对象中。

use problem_details::ProblemDetails;

#[derive(serde::Serialize, serde::Deserialize)]
struct MyExt {
    foo: String,
    bar: u32,
}

let details = ProblemDetails::new()
    .with_title("Extensions test")
    .with_extensions(MyExt {
        foo: "Hello".to_string(),
        bar: 42,
    });

let json = serde_json::to_value(&details).unwrap();

assert_eq!(json, serde_json::json!({
  "title": "Extensions test",
  "foo": "Hello",
  "bar": 42
}));

要使用扩展反序列化,将扩展类型作为泛型参数提供给 ProblemDetails 结构体。

let details: ProblemDetails<MyExt> = serde_json::from_str(json).unwrap();

如果您需要动态扩展,可以使用 HashMap 作为扩展对象。

特性

  • serde: 启用对 ProblemDetails 结构体的 serde 支持(默认启用)
  • json: 启用在使用网页框架集成时序列化为 JSON(默认启用,意味着启用 serde
  • xml: 在使用网页框架集成时启用序列化为 XML(意味着启用 serde
  • axum: 启用与 axum 网页框架的集成,允许将 ProblemDetails 作为响应返回。
  • poem:启用与poem Web 框架的集成,允许返回 ProblemDetails 作为响应和错误。

注意事项

由于未能反序列化包含类型不正确的属性(如RFC 9457 第 3.1 节所要求)的 JSON 值,因此该包不完全符合 RFC 9457。

许可证

根据您的选择,许可方式为以下之一:

依赖项

约 1–12MB
约 137K SLoC