Small actix-web code

I have written a very small and useless piece of Actix-web code just for testing.

use actix_web::{web, get, middleware, Result, Responder, HttpResponse, HttpServer, App};
use serde::Deserialize;

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Index. Default page.")
}

async fn index_get(info: web::Path<(String)>) -> Result<String> {
    Ok(format!("Output: {}", info))
}

async fn index_post(form: web::Form<FormData>) -> Result<String> {
    if form.my_str == "Test" {
        Ok("This is a test".to_string())
    } else {
        Ok(format!("{}", form.my_str))
    }
}

#[derive(Deserialize)]
struct FormData {
    my_str: String,
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {


    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
            .route("/output/{string}", web::get().to(index_get))
            .service(
                web::resource("/")
                .route(web::post().to(index_post))
            )
    })
    .bind("127.0.0.1:8088")?
    .run()
    .await
}

HTML

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <form method="post" action="http://127.0.0.1:8088">
            <input type="text" name="my_str"><br>
            <input type="submit" value="Send">
        </form>
    </body>
</html>

Everything works fine. I'm wondering however if this can be written more efficient? I want to write MVC-style using Actix-web, but I can't find a lot on the internet on how to do that.

Also, wouldn't it be possible to have 3 index() functions but overload each of them depending on the kind of request (get/post/...) and amount of parameters?

Anything else?
Thanks.

Both Rust and Actix are relatively new, you won't find much complex examples, they need to be invented. I recommend looking at frameworks for other languages, like Django or Rails for inspiration. For a start you can use template library like askama to introduce mvc.

There is no concept of function overriding in Rust. Nearest equivalent would be struct with 3 different constructors, which can implement a trait actix can understand, so you could initialize it in different ways depending on request parameters and return it.

2 Likes

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.