如何使用 Rust 关键字创建端点作为查询动态参数?
How to create an endpoint with a Rust keyword as a query dynamic parameter?
我使用 Rocket 库,我需要创建一个包含动态参数 "type"、关键字的端点。
我试过类似的东西,但它没有编译:
#[get("/offers?<type>")]
pub fn offers_get(type: String) -> Status {
unimplemented!()
}
编译器错误:
error: expected argument name, found keyword `type`
rocket 中可以有一个名为 "type" 的参数吗?由于我遵循的规范,我无法重命名参数。
命名查询参数与保留关键字相同存在已知限制。它在 Field Renaming 主题的文档中突出显示。它确实提到了如何使用一些额外的代码来解决您的问题。您的用例示例:
use rocket::request::Form;
#[derive(FromForm)]
struct External {
#[form(field = "type")]
api_type: String
}
#[get("/offers?<ext..>")]
fn offers_get(ext: Form<External>) -> String {
format!("type: '{}'", ext.api_type)
}
对于 /offers?type=Hello,%20World!
的 GET 请求,它应该 return type: 'Hello, World!'
我使用 Rocket 库,我需要创建一个包含动态参数 "type"、关键字的端点。
我试过类似的东西,但它没有编译:
#[get("/offers?<type>")]
pub fn offers_get(type: String) -> Status {
unimplemented!()
}
编译器错误:
error: expected argument name, found keyword `type`
rocket 中可以有一个名为 "type" 的参数吗?由于我遵循的规范,我无法重命名参数。
命名查询参数与保留关键字相同存在已知限制。它在 Field Renaming 主题的文档中突出显示。它确实提到了如何使用一些额外的代码来解决您的问题。您的用例示例:
use rocket::request::Form;
#[derive(FromForm)]
struct External {
#[form(field = "type")]
api_type: String
}
#[get("/offers?<ext..>")]
fn offers_get(ext: Form<External>) -> String {
format!("type: '{}'", ext.api_type)
}
对于 /offers?type=Hello,%20World!
的 GET 请求,它应该 return type: 'Hello, World!'