Rocket 的 rocket_contrib 套件虽然有提供 Json 结构体可以作为路由处理程序的函数的回传值类型,来回传 JSON 格式的数据,但实际用起来却不是很方便。
在实作 JSON 格式的 HTTP API 时,为了使客户端知道 API 的调用是否成功,且若不成功的话也要能知道是什么原因,所以我们可能会回应非标准的 HTTP 状态码来表示错误码。不过其实比较好的实作方式是将错误码放在 HTTP 主体的 JSON 数据中,HTTP 状态码则永远按照标准来回应(甚至也可以只回应 200)。也就是说,回应给客户端的 JSON 格式数据,可能会像是以下这样:
{
"code": 状态码/错误码,
"data": JSON数据
}
但是如果用 Rocket 的 json 特色提供的 Json 结构体来做这件事的话,原先用来串行化成 JSON 数据的类型,就要再使用额外的结构体包装起来。例如:
#[derive(Serialize)]
struct User {
id: i32,
name: String,
}
#[derive(Serialize)]
struct UserWithCode {
code: i32,
user: User,
}
有了 UserWithCode 结构体后才可以再使用 Json 结构体来包裹成 Json<UserWithCode>。
当然,如果要回应的数据类型有很多种的话,可以设计一个有泛型的结构体。例如:
#[derive(Serialize)]
struct User {
id: i32,
name: String,
}
#[derive(Serialize)]
struct DataWithCode<T: Serialize> {
code: i32,
user: T,
}
不过这下子,要作为路由处理程序的函数的回传值类型时就要用 Json 结构体来包裹成 Json<DataWithCode<User>>。这样就变得有太多层泛型了,不是很好用。
JSON Response for Rocket Framework
「JSON Response for Rocket Framework」是笔者开发的套件,用来包裹任意可转为 JSON 格式的数据,并加上状态码机制。
Crates.io
Cargo.toml
使用方法
rocket_json_response 这个 crate 提供的 JSONResponse 结构体,可以用来包裹任意可转为 JSON 格式的数据,使 JSON 数据变成:
{
"code": 状态码,
"data": JSON数据
}
状态码可以是任意有实作同样来自于 rocket_json_response 这个 crate 的 JSONResponseCode 特性的类型,而 Rust 内置的小于或等于 32 比特的整数类型(i8、u32 等)已经有实作 JSONResponseCode 特性了。不过建议还是参考这篇文章来定义枚举,并替它实作 JSONResponseCode 特性。
JSON 数据则可以是任意有实作同样来自于 rocket_json_response 这个 crate 的 ToJSON 特性的类型,Rust 内置的基本数据类型和字符串以及字符串切片都已实作 ToJSON 特性。另外,serde_json 这个 crate 的 Value 枚举也有实作 ToJSON 特性。而 json_gettext 这个 crate 的 JSONGetTextValue 枚举也有实作 ToJSON 特性,有关于 json_gettext 的介绍可以参考这篇文章。
如果要替有实作 Serde 框架的 Serialize 特性的类型实作 ToJSON 特性的话,可以使用 rocket_json_response 提供的 serialize_to_json 宏来快速达成。
如果不想要在回应的 JSON 数据中加上 data 字段,而只有 code 字段的话,这样的 JSON 数据如下所示:
{
"code": 状态码
}
我们可以使用 rocket_json_response 这个 crate 提供的 JSONResponseWithoutData 结构体,来回应以上的 JSON 格式的数据。
典型的 0 状态码表示这个 HTTP API 调用成功了,而非 0 的状态码表示调用失败。因此,不论是 JSONResponse 和 JSONResponseWithoutData 结构体,都提供了 ok 和 err 关联函数来产生实体。前者不需要指定状态码(预设为 0),后者需要指定状态码。
举个例子:
#[macro_use]
extern crate rocket;
use enum_ordinalize::Ordinalize;
use rocket::{
outcome::Outcome,
request::{FromRequest, Outcome as RequestOutcome, Request},
serde::Serialize,
};
use rocket_json_response::{
serialize_to_json, JSONResponse, JSONResponseCode, JSONResponseWithoutData,
};
#[derive(Serialize)]
struct User {
id: i32,
name: String,
}
serialize_to_json!(User);
#[derive(Ordinalize)]
#[repr(i32)]
pub enum ErrorCode {
IncorrectIDFormat = 100,
}
impl JSONResponseCode for ErrorCode {
fn get_code(&self) -> i32 {
self.ordinal()
}
}
struct UserAgent<'a> {
user_agent: &'a str,
}
#[async_trait]
impl<'r> FromRequest<'r> for UserAgent<'r> {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> RequestOutcome<Self, Self::Error> {
let user_agent: Option<&str> = request.headers().get("user-agent").next();
match user_agent {
Some(user_agent) => Outcome::Success(UserAgent {
user_agent,
}),
None => Outcome::Forward(()),
}
}
}
#[get("/")]
fn alive() -> JSONResponseWithoutData {
JSONResponseWithoutData::ok()
}
#[get("/<id>")]
fn id(id: u32) -> JSONResponse<'static, u32> {
JSONResponse::ok(id)
}
#[get("/<id>", rank = 1)]
fn id_str(id: String) -> JSONResponse<'static, String> {
JSONResponse::err(ErrorCode::IncorrectIDFormat, id)
}
#[get("/user/magiclen")]
fn user() -> JSONResponse<'static, User> {
JSONResponse::ok(User {
id: 0, name: "Magic Len".to_string()
})
}
#[get("/client/user-agent")]
fn user_agent(user_agent: UserAgent) -> JSONResponse<&str> {
JSONResponse::ok(user_agent.user_agent)
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![alive])
.mount("/", routes![id, id_str])
.mount("/", routes![user])
.mount("/", routes![user_agent])
}
比较需要注意的是,在这个例子中,UserAgent 这个请求守卫会去取得 HTTP 请求中的 User-Agent 标头字段,但它不会将字段值拷贝成新的字符串,所以这时候 JSONResponse 的泛型生命周期参数就派上用场啦!在 user_agent 路由处理程序里,沿用了 User-Agent 字段值的生命周期,使它从接收到回应都不会被另外拷贝!
另外,虽然在例子中没有见到,但 JSONResponse 的泛型类型参数如果被省略掉的话,该泛型类型参数预设的类型会是 JSONGetTextValue<'a>。因为 JSONGetTextValue 枚举可以用来表示所有类型的 JSON 数据(对象、数组、字符串、数值、布尔值),所以不太需要被明写出来。(不预设使用 serde_json 这个 crate 的 Value 枚举的原因是,Value 枚举并没有办法直接保存字符串切片,所以如果要用它表示 JSON 字符串,一定要将字符串切片转成字符串才行,然而这样又需要进行拷贝的动作了。)
