Search code examples
rustactix-web

How can i get the code out of this url with actix web?


Im trying to get the code out of this link: http://127.0.0.1:8000/modnpc/discordredirect?code=5645656465

I thought i could do like this:

#[get("/modnpc/discordredirect?code={code}")]
async fn discordredirect(code: web::Path<String>, data: web::Data<AppState>) -> impl Responder {
    requestcounterchangebyone(data).await;
    format!("This is the code: {}", &code)
}

and add this like this to the app:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(Env::default().default_filter_or("info"));

    HttpServer::new(|| {
        App::new()
            //Logger
            .wrap(Logger::default())
            .wrap(Logger::new("%a %{User-Agent}i"))
            //App State
            .app_data(web::Data::new(AppState {
                app_name: String::from("Jeran Studios Actix Webserver"),
                app_time: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                app_request_counter: Mutex::new(0),
            }))
            //Service of the single pages
            .service(index)
            .service(current_temperature)
            .service(status)
            .service(hello)
            .service(discordredirect)
            .default_service(web::route().to(not_found)) //page does not exist
    })
    .bind(("127.0.0.1", 8000))?
    .workers(4)
    .run()
    .await
}

but somehow i always get the default_service:

async fn not_found() -> Result<HttpResponse> {
    Ok(HttpResponse::build(StatusCode::OK)
        .content_type("text; charset=utf-8")
        .body("<h1>ERROR 404: This page does not exist.</h1>"))
}

Solution

  • The ?code=... part is the query and not part of the path. You can handle it with a Query extractor along with a deserializable type that expresses all the query parameters.

    Something like this:

    #[derive(Deserialize)]
    struct RedirectParams {
        code: String,
    }
    
    #[get("/modnpc/discordredirect")]
    async fn discordredirect(
        params: web::Query<RedirectParams>,
        data: web::Data<AppState>,
    ) -> impl Responder {
        format!("This is the code: {}", params.code)
    }