前言
如果你对控制台情有独钟,必然会接触到命令行传参。对使用者而言,一份优雅的命令列表,错误提示能增进软件的好感。 但对开发者而言,维护一份复杂的命令列表是头疼的。重复的命令行参数,随着子参数增多,不会规范管理,都会是代码难以阅读。
为了提升效率,减轻负担,本文强烈推荐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
请求效果: