前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rust:axum学习笔记(1) hello world

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

作者头像
菩提树下的杨过
发布2021-12-28 08:50:25
5K0
发布2021-12-28 08:50:25
举报
文章被收录于专栏:菩提树下的杨过

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

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

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

代码语言:javascript
复制
[dependencies]
axum="0.4.3"
tokio = { version = "1.0", features = ["full"] }

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

代码语言:javascript
复制
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();
}

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

再加几个路由:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-12-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档