rust ~ Webフレームワーク ~ 

RustのWebフレームワーク[actix-web](https://github.com/actix/actix-web)のサンプルを実行し、その結果をまとめました。

#環境
Ubuntu 18.04

#インストール

```
git clone https://github.com/actix/actix-web.git
```

#サンプル

サンプルの種類を確認します。

```
$ cargo run --example
error: "--example" takes one argument.
Available examples:
    basic
    on_connect
    uds
```
次に各サンプルを試して行きます。

##サンプル1 basic

```
$ cargo run --example basic
    Finished dev [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/examples/basic`
[2021-04-03T08:09:44Z INFO  actix_server::builder] Starting 1 workers
[2021-04-03T08:09:44Z INFO  actix_server::builder] Starting "actix-web-service-127.0.0.1:8080" service on 127.0.0.1:8080
```
ウェブブラウザから動作を確認します。
```http://0.0.0.0:8080```を開きます。
![Screenshot from 2021-04-03 16-58-38.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/589906/7790ec15-f2a1-c256-5fc2-3f85bae92919.png)

ブラウザ上に```Hello world!```と表示されていることが確認できます。

##サンプル2 on_connect

```
$ cargo run --example on_connect
```
ウェブブラウザから動作を確認します。
![Screenshot from 2021-04-03 17-20-57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/589906/7bc73d6f-1eaf-98e9-7377-8faf8193f2a5.png)
サーバーの状態が表示されます。

##サンプル3 

```
$ cargo run --example uds
    Finished dev [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/examples/uds`
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
```
こちらのサンプルは、エラーが出て動作の確認はできませんでした。

#ソースコード
各サンプルのコードを添付します。

```rust:basic.rs
use actix_web::{get, middleware, web, App, HttpRequest, HttpResponse, HttpServer};

#[get("/resource1/{name}/index.html")]
async fn index(req: HttpRequest, name: web::Path<String>) -> String {
    println!("REQ: {:?}", req);
    format!("Hello: {}!\r\n", name)
}

async fn index_async(req: HttpRequest) -> &'static str {
    println!("REQ: {:?}", req);
    "Hello world!\r\n"
}

#[get("/")]
async fn no_params() -> &'static str {
    "Hello world!\r\n"
}

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

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
            .wrap(middleware::Compress::default())
            .wrap(middleware::Logger::default())
            .service(index)
            .service(no_params)
            .service(
                web::resource("/resource2/index.html")
                    .wrap(middleware::DefaultHeaders::new().header("X-Version-R2", "0.3"))
                    .default_service(web::route().to(HttpResponse::MethodNotAllowed))
                    .route(web::get().to(index_async)),
            )
            .service(web::resource("/test1.html").to(|| async { "Test\r\n" }))
    })
    .bind("127.0.0.1:8080")?
    .workers(1)
    .run()
    .await
}
```

```rust:on_connect.rs
//! This example shows how to use `actix_web::HttpServer::on_connect` to access a lower-level socket
//! properties and pass them to a handler through request-local data.
//!
//! For an example of extracting a client TLS certificate, see:
//! <https://github.com/actix/examples/tree/HEAD/security/rustls-client-cert>

use std::{any::Any, io, net::SocketAddr};

use actix_web::{dev::Extensions, rt::net::TcpStream, web, App, HttpServer};

#[derive(Debug, Clone)]
struct ConnectionInfo {
    bind: SocketAddr,
    peer: SocketAddr,
    ttl: Option<u32>,
}

async fn route_whoami(conn_info: web::ReqData<ConnectionInfo>) -> String {
    format!(
        "Here is some info about your connection:\n\n{:#?}",
        conn_info
    )
}

fn get_conn_info(connection: &dyn Any, data: &mut Extensions) {
    if let Some(sock) = connection.downcast_ref::<TcpStream>() {
        data.insert(ConnectionInfo {
            bind: sock.local_addr().unwrap(),
            peer: sock.peer_addr().unwrap(),
            ttl: sock.ttl().ok(),
        });
    } else {
        unreachable!("connection should only be plaintext since no TLS is set up");
    }
}

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

    HttpServer::new(|| App::new().default_service(web::to(route_whoami)))
        .on_connect(get_conn_info)
        .bind(("127.0.0.1", 8080))?
        .workers(1)
        .run()
        .await
}
```

```rust:uds.rs
use actix_web::{get, web, HttpRequest};
#[cfg(unix)]
use actix_web::{middleware, App, Error, HttpResponse, HttpServer};

#[get("/resource1/{name}/index.html")]
async fn index(req: HttpRequest, name: web::Path<String>) -> String {
    println!("REQ: {:?}", req);
    format!("Hello: {}!\r\n", name)
}

#[cfg(unix)]
async fn index_async(req: HttpRequest) -> Result<&'static str, Error> {
    println!("REQ: {:?}", req);
    Ok("Hello world!\r\n")
}

#[get("/")]
async fn no_params() -> &'static str {
    "Hello world!\r\n"
}

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

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
            .wrap(middleware::Compress::default())
            .wrap(middleware::Logger::default())
            .service(index)
            .service(no_params)
            .service(
                web::resource("/resource2/index.html")
                    .wrap(middleware::DefaultHeaders::new().header("X-Version-R2", "0.3"))
                    .default_service(web::route().to(HttpResponse::MethodNotAllowed))
                    .route(web::get().to(index_async)),
            )
            .service(web::resource("/test1.html").to(|| async { "Test\r\n" }))
    })
    .bind_uds("/Users/fafhrd91/uds-test")?
    .workers(1)
    .run()
    .await
}

#[cfg(not(unix))]
fn main() {}
```