Rust 以命令行形式启动web端口

前言

如果你对控制台情有独钟,必然会接触到命令行传参。对使用者而言,一份优雅的命令列表,错误提示能增进软件的好感。 但对开发者而言,维护一份复杂的命令列表是头疼的。重复的命令行参数,随着子参数增多,不会规范管理,都会是代码难以阅读。

为了提升效率,减轻负担,本文强烈推荐clap库。

介绍

clap是一个简单易用,功能强大的命令行参数解析库。

使用

clap 允许多中方式指定我们的命令行。支持常规的 Rust 方法调用、宏或者YAML配置。

1. Cargo.toml引入第三方库

[package]
name = "axum"
version = "0.1.0"
authors = ["chh <1400152400@qq.com>"]
edition = "2021"

[dependencies]
axum = "0.6.18"
tokio = { version = "1.0", features = ["full"] }
clap= "3.1.18"

2. 代码示例

main.rs 代码如下:

use axum::Router;
use axum::routing::get;

#[tokio::main]
async fn main() {
    let name = env!("CARGO_PKG_NAME");
    let version = env!("CARGO_PKG_VERSION");
    let author = env!("CARGO_PKG_AUTHORS");

    let matches = clap::App::new(name)
        .version(version)
        .author(author)
        .about("Learn use Rust Crate!")
        .arg(clap::Arg::with_name("command").required(true).index(1))
        .arg(clap::Arg::with_name("param").required(true).index(2))
        .get_matches();

    let param = matches.value_of("param").unwrap_or_default();

    match matches.value_of("command").unwrap_or_default() {
        "service" => start_web(param.parse::<i32>().unwrap_or(8000)).await,
        other => panic!("Unknown command {}", other),
    };
}

async fn start_web(port: i32) {
    let app = Router::new()
        .route("/", get(root))  // http://127.0.0.1:3000
        .route("/foo", get(get_foo).post(post_foo)) // http://127.0.0.1:3000/foo
        .route("/foo/bar", get(foo_bar)); // http://127.0.0.1:3000/foo/bar

    axum::Server::bind(&format!("{}:{}", "0.0.0.0", &port).parse().unwrap()).serve(app.into_make_service()).await.expect("connect-error");
}

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")
}

3. 编译可执行文件

cargo build --release

我们使用version(),author()和 about()方法,提供程序的的一般信息。clap会自动添加两个参数:–help和–version(或他们的简短形式-h和-V)。

运行你的可执行文件,并在跟随–help参数

.\target\release\axum.exe --help

控制台输出:

axum 0.1.0
chh <1400152400@qq.com>
Learn use Rust Crate!

USAGE:
    axum.exe <command> <param>

ARGS:
    <command>
    <param>

OPTIONS:
    -h, --help       Print help information
    -V, --version    Print version information

4. 命令行形式启动端口

.\target\release\axum.exe service 8080

请求效果:

http://localhost:8080/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一碗情深

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值