程式語言 - Rust - Web Server(Form)



參考資訊:
https://www.rust-lang.org/learn/get-started
http://bzz.wallizard.com:8081/share/books/RUST/Programming%20Rust%202nd%20Edition.pdf

產生樣板

$ cargo new hello
$ cd hello

Cargo.toml

[package]
name = "hello"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "1.0.8"
serde = { version = "1.0", features = ["derive"] }

src/main.rs

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

#[derive(Deserialize)]
struct MyStruct {
    v1: u64,
    v2: u64,
}

fn main() {
    let server = HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(get_index))
            .route("/test", web::post().to(post_test))
    });

    server
        .bind("127.0.0.1:3000").expect("error binding server to address")
        .run().expect("error running server");
}

fn get_index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type("text/html")
        .body(r#"
              <title>Input Test</title>
              <form action = "/test" method = "post">
              <input type = "text" name = "v1" />
              <input type = "text" name = "v2" />
              <button type = "submit">Send</button>
              </form>
              "#,
        )
}

fn post_test(form: web::Form<MyStruct>) -> HttpResponse {
    let response = format!("v1:{}<br>v2:{}\r\n", form.v1, form.v2);
 
    HttpResponse::Ok()
        .content_type("text/html")
        .body(response)
}

執行

$ cargo run

開啟網頁並且輸入http://127.0.0.1:3000