🌞

actix-web入门实践

准备rustup、rustc、cargo开始hello worldactix-web本身是一个crate;初始一个项目cargo init // 初始化一个项目 then… 在Cargo.to

文链接在语雀:https://www.yuque.com/wumingshi/rkh1qq/

准备

rustup、rustc、cargo

开始hello world

actix-web本身是一个crate;

初始一个项目

cargo init // 初始化一个项目

then...

在Cargo.toml加入一个依赖
[package]
name = "actix-test"
version = "0.1.0"
authors = [""]
edition = "2018"

[dependencies]
actix-web = "0.7"


then...

cargo check 可以安装依赖

then...

src/main.rs写代码就好了

extern crate actix_web;
use actix_web::{server, App, HttpRequest};
fn main() {
    println!("hello");
    server::new(|| App::new().resource("/", |r| r.f(index)))
        .bind("127.0.0.8888")
        .unwrap()
        .run();
}

fn index(_req: &HttpRequest) -> &'static str {
    "hello world"
}

then...

cargo run

嗯 就是这么简单,一个简单的静态服务器就完成了。


关于应用

actix-web提供路由、中间件、请求预处理、websocket协议处理等,完全具备开发一个大型应用的能力,并且完全基于rust  stable版本构建。actix-web server由一个App实例构成,在这个实例上进行资源和中间件的挂载,并且实现不同handlers的数据共享。同时一个server可以承托多个应用实例,例如:

这里需要理解rust闭包的用法

extern crate actix_web;
use actix_web::{server, App, HttpRequest, pred};
use std::cell::Cell;
fn main() {
    println!("hello");
    server::new(|| vec![
        App::with_state(AppState { counter: Cell::new(0) }).prefix("/app1").filter(pred::Host("127.0.0.1:8088")).resource("/", |r| r.f(|r| index(r, "1"))),
        App::with_state(AppState { counter: Cell::new(0) }).prefix("/app2").resource("/", |r| r.f(|r| index(r, "2"))),
        App::with_state(AppState { counter: Cell::new(0) }).resource("/", |r| r.f(|r| index(r, "3")))])
        .bind("127.0.0.1:8088")
        .unwrap()
        .run();
}

// router和resource可以进行状态共享
struct AppState{
    counter: Cell<usize>
}

fn index(_req: &HttpRequest<AppState>, text: &'static str) -> &'static str {
    let count = _req.state().counter.get() + 1;
    println!("state is {}", count);
    _req.state().counter.set(count);
    text
}

server会依次进行应用的匹配,从前往后,如果app1 app2都无法匹配到,则默认进入第三个应用

http://127.0.0.1:8088/app1/ => 1

http://127.0.0.1:8088/app2/ => 2

http://127.0.0.1:8088 => 3




updatedupdated2023-10-312023-10-31