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方法的路由。可以测试一下:

猜你喜欢

转载自blog.csdn.net/love906897406/article/details/125999405