大家好,我是砸锅。一个摸鱼八年的后端开发。熟悉 Go、Lua。第五天还是继续和大家一起学习 Rust😊
第五天是学习写一个小工具,这个工具是可以通过命令行解析之后,处理各种子命令和参数,验证用户的输入,并且将这些输入转换到内部的参数。
然后通过解析的参数来发送一个 HTTP 请求,获取相应后彩色显示出来。看上去有点像 postman
用到了下面这些工具:
- clap,官方推荐的命令行解析工具
- reqwest,HTTP 客户端
- colored,用来彩色显示输出内容
- anyhow,错误处理
- jsonxf,格式化 JSON
- mime,处理 mime 类型
- tokio,异步处理
Cargo.toml
[package]
name = "httpie"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1" # 错误处理
clap = { version = "3", features = ["derive"] } # 命令行解析
colored = "2" # 命令行终端多彩显示
jsonxf = "1.1" # JSON pretty print 格式化
mime = "0.3" # 处理 mime 类型
reqwest = { version = "0.11", default-feature = false, features = ["json","rustls-tls"] } # HTTP 客户端
tokio = { version = "1", features = ["full"] } # 异步处理库
syntect = "4"
main.rs
use clap::{AppSettings, Clap};
// 定义 HTTPie 的 CLI 的主入口, 包含若干个自命令
/// A naive httpie implementation wite Rust
#[derive(Clap, Debug)]
#[clap(version = "1.0", author = "Jason <jason@gmail.com>")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Clap, Debug)]
enum SubCommand {
Get(Get),
Post(Post),
}
struct Get {
url: String,
}
struct Post {
url: String,
body: Vec<String>,
}
fn main() {
let opts: Opts = Opts::parse();
println!("{:?}", opts);
}
暂时代码写到这,明天再继续深入优化这个小工具的实现。在这里也给大家拜个早年,新年快乐