Rust web 框架 axum (一): 安装及 hello world

更新日期: 2023-11-09 阅读次数: 1896 字数: 648 分类: rust

为何要尝试 axum

最近在看两本 Rust 的教程,一本在早上上厕所时看,一本在班车上看/睡觉前看。这两个作者确实经验丰富,文笔也非常有趣,比刷抖音愉快多了。是个很好的放松方式。

但是光看不练,学习效率就很低,所以决定一边看书,一边写点 Rust 代码巩固一下。

虽然我对于 Rust 还没有实现的项目用途,但可以写一点 web 小工具,毕竟每天实际工作中每天都会遇到一些繁琐的手动操作需要自动化。之前学习 golang 就是,练手写了一个微信小程序的后台,写完后感觉对 golang 就尽在掌握了。。。这个小程序至今已积累了 30 万用户,日活 2k,也非常有成就感。

axum 简介

axum is a web application framework that focuses on ergonomics (人体工程学) and modularity (模块化).

创建项目

如果没有安装 rust cargo,可以参考 使用国内源安装 Rust

新建一个名为 rust_tool 的项目。

cargo new rust_tool

hello world 代码

用下面代码替换掉 src/main.rs 中的默认代码:

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();
}

运行报错

> cargo run
   Compiling rust_tool v0.1.0 (/mnt/d/work/rust_tool)
error[E0433]: failed to resolve: use of undeclared crate or module `axum`
 --> src/main.rs:1:5
  |
1 | use axum::{
  |     ^^^^ use of undeclared crate or module `axum`

error[E0432]: unresolved import `axum`
 --> src/main.rs:1:5
  |
1 | use axum::{
  |     ^^^^ use of undeclared crate or module `axum`

看来是没有安装相关的依赖包。这点不如 go 的包管理器方便,至少能给出安装提示命令。

Cargo.toml 添加依赖

打开配置文件 Cargo.toml, 在 dependencies 下加入 axum 和 tokio 两个依赖。

[package]
name = "rust_tool"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.6"
tokio = { version = "1.0", features = ["full"] }
  • 目前(2023-11-04 星期六), axum 的最新版本为 0.6
  • tokio 是一个异步的 async 库。

或者通过 cargo add 命令来添加依赖包:

cargo add axum \
    tokio -F tokio/full 

再次运行

cargo run

就能看到 cargo 在自动安装依赖了。

当看到

Compiling rust_tool v0.1.0 (/mnt/d/work/rust_tool)
    Finished dev [unoptimized + debuginfo] target(s) in 3m 28s
     Running `target/debug/rust_tool`

说明编译完成,并运行了。

此时,打开浏览器输入

http://localhost:3000

即可看到 Hello, World! 的字样。

依赖包下载慢

参考:

https://mirrors.tuna.tsinghua.edu.cn/help/rustup/

若要长期启用镜像源,执行:

# for bash
echo 'export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup' >> ~/.bash_profile
echo 'export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup' >> ~/.bash_profile

# for fish
echo 'set -x RUSTUP_UPDATE_ROOT https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup' >> ~/.config/fish/config.fish
echo 'set -x RUSTUP_DIST_SERVER https://mirrors.tuna.tsinghua.edu.cn/rustup' >> ~/.config/fish/config.fish

查看合集

📖 Rust web 框架 axum 教程:从入门到遥遥领先

参考

  • https://github.com/tokio-rs/axum
  • https://docs.rs/axum/latest/axum/
  • 针对新手的教程 https://github.com/tokio-rs/axum/blob/main/ECOSYSTEM.md#tutorials

tags: axum

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式