Rust:axum学习笔记(1) hello world

axum是Rust生态的web框架新秀,虽然项目成立不久,但github上的star数已超2.8k,其底层依赖的是高性能的Tokio,Tokio这货就不多说了,借用知乎《深入浅出Rust异步编程之Tokio》上的一张图:

Rust中的Tokio几乎是同类框架的性能天花板了,而axum在Tokio基础上构建,起点就站在巨人的肩膀上。

先来一个Hello World的入门示例:

[dependencies]
axum="0.4.3"
tokio = { version = "1.0", features = ["full"] }

复制

添加上面的依赖项后,就可以编码了:

use axum::{
    routing::get,
    Router,
};


#[tokio::main]
async fn main() {
    // build our application with a single route
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));

    // run it with hyper on localhost:3000
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

复制

启动后,浏览器里跑一下:

再加几个路由:

use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    // our router
    let app = Router::new()
        .route("/", get(root))
        .route("/foo", get(get_foo).post(post_foo))
        .route("/foo/bar", get(foo_bar));

    // run it with hyper on localhost:3000
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

// which calls one of these handlers
async fn root() -> String {
    String::from("hello axum")
}
async fn get_foo() -> String {
    String::from("get:foo")
}
async fn post_foo() -> String {
    String::from("post:foo")
}
async fn foo_bar() -> String {
    String::from("foo:bar")
}

复制

注意:/foo同时绑定了GET及POST方法的路由。可以测试一下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值