rwf2 / Rocket

A web framework for Rust.
https://rocket.rs
Other
23.59k stars 1.52k forks source link

Implement `FromForm` for `Range` #2759

Closed RuboGubo closed 1 month ago

RuboGubo commented 2 months ago

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 https://github.com/rwf2/Rocket/issues/2736#issuecomment-2002021860

SergioBenitez commented 2 months ago

Sure. I'm happy to accept an impl.