Axum, button, get request

Hey, so is there a more robust way to write this? like is there a way to directly serialize data into a uri? and no i dont want to use javascript at all. im mainly talking about how i handled the query. i felt it was poor, i just want a setup that works with a full fledged website

use axum::{extract::Query, response::Redirect, routing::get, Router};
use maud::{html, Markup, Render};

mod css;
use css::Css;
use serde::Deserialize;
use tower_http::services::ServeFile;

#[derive(Deserialize)]
struct Params {
    message: Option<String>,
}

#[tokio::main]
async fn main() {
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app()).await.unwrap();
}

fn app() -> Router {
    Router::new()
        .route("/", get(root))
        .route("/hello", get(hello))
        .route_service("/styles.css", ServeFile::new("assets/styles.css"))
}

async fn root(Query(params): Query<Params>) -> Markup {
    let css = Css("styles.css").render();
    let message = params.message.unwrap_or_default();

    html! {
        (css)
        form method="get" action="/hello" {
            button type="submit" {
                "Click me!"
            }
        }
        (message)
    }
}

async fn hello() -> Redirect {
    Redirect::to("/?message=hello")
}

There are many. serde_urlencoded is one of them.

do you know how to use it?

You can learn how to use it. There's a link to the crate's documentation.

like this?

async fn hello() -> Redirect {
    let form = Params {
        message: Some("hello".to_owned()),
    };
    let query_string = serde_urlencoded::to_string(&form).unwrap();
    Redirect::to(&format!("/?{}", query_string))
}

Yes, that's one way to use it :slight_smile:.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.