Rust https web server 范例

原创
2020/04/29 14:21
阅读数 462

Hyper 比较底层,不适合用于直接生产。适合基于它做封装。 Actix-web 文档比较友好,速度也不错。 Rocket 采用大量的宏,不适合 IDE 编写提示。

最后我们采用 Actix-web 作为我们的生产环境。 为了安全,我们采用 https。自己签名省钱。

openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'

Cargo.toml:

[package]
name = "test-actix-web"
version = "0.1.0"
authors = ["hh <hh@xx.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = {version="2.0", features = ["openssl"]}
actix-rt = "1.0"
openssl = { version="0.10" }
tokio = "0.2"

src/main.rs:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

// curl -k https://localhost:8088/again
// curl -x http://proxyip:port/ url
async fn index2() -> impl Responder {

    tokio::time::delay_for(std::time::Duration::from_secs(2)).await;

    HttpResponse::Ok().body("Hello world again!")
}


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

    let mut builder =
        SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();

    // openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'
    builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
    builder.set_certificate_chain_file("cert.pem").unwrap();

    let route = || {
        App::new()
        .route("/", web::get().to(index))
        .route("/again", web::get().to(index2))
    };

    HttpServer::new(route).bind_openssl("127.0.0.1:8088", builder)?.run().await

    // HttpServer::new(route)
    //     .workers(4)
    //     .bind("127.0.0.1:8088")?
    //     .run()
    //     .await
}

检测:

curl -k https://localhost:8088/again
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部