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

 

參考鏈接:

https://docs.rs/axum/0.4.3/axum/index.html

https://zhuanlan.zhihu.com/p/107820568?from_voters_page=true

https://docs.rs/axum/0.4.3/axum/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM