The target

Submit the form to the back end, and then accept the returned data

Hello,world!

Actix-web is a Web framework developed using Rust. It’s powerful, fast and practical, and one of the best choices for Web development with Rust — why bother?

As usual, choose to create a hello_world program to get a feel for actix-Web.

Start by creating a new project called hello_world using Cargo.

cargo new hello_world
cd hello_world
Copy the code

Next, in the hello_world directory, add Cargo. Toml:

[dependencies]
actix-web = "3"
Copy the code

Add Actix-Web as a dependency for your project.

Let’s step through Hello, World! The code of

use actix_web::{get, App, HttpResponse, HttpServer, Responder};

// Route specifies the path (get)
#[get("/")]
async fn hello() - >impl Responder {
    // Returns an Http response with a Hello,world message body
    HttpResponse::Ok().body("Hello,world!")}// Mark async main as the entry point to the Actix system.
#[actix_web::main]
async fn main() -> std::io::Result< > () {// Create an HTTP server
    HttpServer::new(|| {
        App::new()// Create an application
            .service(hello)// Use the hello function as a service
    })
    .bind("127.0.0.1:8080")?// Bind to the specified socket address
    .run()// Start listening
    .await
}
Copy the code

Start the service by running the command cargo run in the hello_world directory.

Then launch the browser and enter the socket address we specified: 127.0.0.1:8080.

FromRequest trait

When we send a request to an address, it usually comes with some additional information, and the FromRequest Trait defines some format for extracting the request information.

In the simplest case, the request body is a segment of text that needs to be received:

use actix_web::{post, App, HttpResponse, HttpServer, Responder};

// Routing /post requests
#[post("/post")]
async fn get_text(txt: String) -> impl Responder {
    HttpResponse::Ok().body(format! ("Received successfully: {}", txt))
}

// Mark async main as the entry point to the Actix system.
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Create an HTTP server
    HttpServer: :new(| | {App: :new(a)// Create an application
            .service(get_text)
    })
    .bind("127.0.0.1:8080")? // Bind to the specified socket address
    .run() // Start listening
    .await
}
Copy the code

For additional formats, see the Trait Actix_Web ::FromRequest

Submit the form

Build the page

Start by building a basic page with Html that can submit a form. We create a new project form, then create a folder called Pages under the Form directory and create the file index.html inside.

Add dependencies:

[dependencies]
actix-web = "3"
serde = { version = "1", features = ["derive"]}Copy the code

Write Html:

<! DOCTYPEhtml>
<html>

<body>
    <h3>Who's calling, please?</h3>
    <form action=/post method=POST>
        <button type=submit>I am a:</button>
        <input name="name">
    </form>
</body>

</html>
Copy the code

A very standard submission form:

Next we step through the Rust code:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};

// Form format, corresponding to name in Html
#[derive(Serialize, Deserialize)]
pub struct Person {
    name: String,}// Displays the initial (pages/index.html) page
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")/ / format
        .body(include_str!(".. /pages/index.html"))// Read the file as the corresponding body
}

async fn post(p: web::Form<Person>) -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")// Prevent garbled characters
        .body(format!("Welcome to {}", p.name))// Read the form contents
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            // Implement GET and POST requests in a different way
            .service(web::resource("/").route(web::get().to(index)))// Route root directory
            .service(web::resource("/post").route(web::post().to(post)))// Route /post directory
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
Copy the code

Then run and submit:

Welcome to comment and exchange!