Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an endpoint with a Rust keyword as a query dynamic parameter?

I use the Rocket library and I need to create an endpoint which contains the dynamic parameter "type", a keyword.

I tried something like this but it does not compile:

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

compiler error:

error: expected argument name, found keyword `type`

Is it possible to have a parameter named "type" in rocket? I can't rename the parameter because of the specification I'm following.

like image 466
sbagin13 Avatar asked Jan 05 '19 19:01

sbagin13


1 Answers

There is a known limitation for naming query parameters same as reserved keywords. It is highlighted in documentation on topic of Field Renaming. It does mention how to solve your problem with a little bit of extra code. Example for your use case:

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)
}

For GET request of /offers?type=Hello,%20World! it should return type: 'Hello, World!'

like image 183
TSB99X Avatar answered Sep 20 '22 03:09

TSB99X