rwf2 / Rocket

A web framework for Rust.

Home Page:https://rocket.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement `FromForm` for `Range`

RuboGubo opened this issue · comments

Hi, I'm back, I had to temporarily step away from Foss, but i'm back and happy to respond.

In terms of what you said: I ment FromFormField, which would not work anyway as Range<T> would most likely have to be implemented over two fields.
In terms of what it should look like in a form, you would most likely have two fields in the form <range_var_name>.start and <range_var_name>.end. I chose those names as that is what the Range<T> type uses internally.

Example HTML Rendered:
grafik

Example HTML Source:

<form class="Search" id="PrimeNumberSearch" action="{{https_url_for(request, 'SearchPrimeResult')}}" target="PrimeNumberSearchIF">
    <input type="number" name="prime_range.start" placeholder="min prime">
    <input type="number" name="prime_range.end" placeholder="max prime">
    <button class="submit" type="submit"></button>
</form>

Example Rocket Function:

#[derive(Debug, FromForm)]
struct FormData {
    prime_range: Range<i64>,
}

#[get("/prime", data="<form>")]
async fn get_prime_form(db: &PrimeDB, form: Form<FormData>) -> Result<Json<Vec<i64>>, Status> {
    Ok(Json(get_primes(db, form.into_inner().prime_range).await?))
}

And it would of course also work outside of a struct:

#[get("/prime", data="<form>")]
async fn get_prime_form(db: &PrimeDB, form: Form<Range<i64>>) -> Result<Json<Vec<i64>>, Status> {
    Ok(Json(get_primes(db, form.into_inner()).await?))
}
<form class="Search" id="PrimeNumberSearch" action="{{https_url_for(request, 'SearchPrimeResult')}}" target="PrimeNumberSearchIF">
    <input type="number" name="start" placeholder="min prime">
    <input type="number" name="end" placeholder="max prime">
    <button class="submit" type="submit"></button>
</form>

Originally posted by @RuboGubo in #2736 (comment)

Sure. I'm happy to accept an impl.