zacharygolba / via

A multi-threaded async web framework for people who appreciate simplicity.
Apache License 2.0
1 stars 0 forks source link

feat(via): optionally decode path and query params #21

Closed zacharygolba closed 1 month ago

zacharygolba commented 1 month ago

Adds support for encoded URL path parameters. Also makes percent-decoding parameters optional by introducing the decode method to Param and QueryParam. Below is a modified version of the hello responder from the hello-world example that was used to test this feature.

use std::fmt::Write;
use via::{Error, Next, Request};

async fn hello(request: Request, _: Next) -> Result<String, Error> {
    // Attempt to parse the query parameter `n` to a `usize` no greater than
    // 1000. If the query parameter doesn't exist or can't be converted to a
    // `usize`, default to 1.
    let n = request.query("n").first().parse().unwrap_or(1).min(1000);

    // Get a reference to the path parameter `name` from the request uri.
    let name = request.param("name").percent_decode().into_result()?;

    // Create a greeting message with the provided name.
    let mut message = String::new();

    // Write a greeting message to the `message` buffer `n` times.
    for _ in 0..n {
        writeln!(&mut message, "Hello, {}!", name)?;
    }

    // Print a message to the console for each friend of the person with `name`.
    for friend in request
        .query("friend")
        .percent_decode()
        .into_iter()
        .take(100)
    {
        println!(
            "Hello, {}! Any friend of {} is a friend of mine.",
            friend, name
        );
    }

    // Send a response with our greeting message, repeated `n` times.
    Ok(message)
}