【问题标题】:How to create an endpoint with a Rust keyword as a query dynamic parameter?如何使用 Rust 关键字作为查询动态参数创建端点?
【发布时间】:2019-05-31 23:53:40
【问题描述】:

我使用 Rocket 库,我需要创建一个端点,其中包含动态参数“type”,一个关键字。

我尝试了类似的方法,但无法编译:

#[get("/offers?<type>")]
pub fn offers_get(type: String) -> Status {
    unimplemented!()
}

编译器错误:

error: expected argument name, found keyword `type`

火箭中是否可以有一个名为“type”的参数?由于我遵循的规范,我无法重命名参数。

【问题讨论】:

  • 你应该可以使用raw identifier, r#type
  • 然后我得到这样的错误:帮助:消息:"__rocket_param_r#type" 不是有效的标识符
  • 听起来像一个错误。你应该提出问题。

标签: rust rust-rocket


【解决方案1】:

将查询参数命名为与保留关键字相同有一个已知限制。它在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 请求,它应该返回type: 'Hello, World!'

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2023-01-10
    • 2019-07-24
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多