编写第一个CLI小程序练手。
项目需求
- 访问一个网站,输出页面内容成md文件。
初始化项目
cargo new learning-05
- 使用vs code 打开项目。
添加依赖
- 修改Cargo.toml
- 引入 reqwest 和 html2md
- reqwest 是一个http客户端
- html2md 顾名思义就是html转markdown
reqwest = { version = "0.11", features = ["blocking"]}
html2md = "0.2"%
编写代码
use std::fs;
fn main() {
let url = "https://z201.vip";
let output = "z201.md";
println!("url {} output {}",url,output);
let body = reqwest::blocking::get(url).unwrap().text().unwrap();
println!("Converting html to markdown...");
let md = html2md::parse_html(&body);
fs::write(output, md.as_bytes()).unwrap();
println!("Converted markdown has been saved in {}.", output);
}
- Console
url https://z201.vip output z201.md
Converting html to markdown...
Converted markdown has been saved in z201.md.
迭代代码
版本一
- 这里将url 和 output作为参数。
use std::fs;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
println!("args {:?} ",args);
// 获取第一个参数
let url = &args[1];
// 获取第二个参数
let output = &args[2];
// 判断参数是否为空,不知道这个是否有效。
assert_eq!(url.is_empty(),false);
assert_eq!(output.is_empty(),false);
println!("url {} output {}",url,output);
let body = reqwest::blocking::get(url).unwrap().text().unwrap();
println!("Converting html to markdown...");
let md = html2md::parse_html(&body);
fs::write(output, md.as_bytes()).unwrap();
println!("Converted markdown has been saved in {}.", output);
}
- Console
➜ learning-05 git:(master) ✗ cargo run https://z201.vip z201.md
Finished dev [unoptimized + debuginfo] target(s) in 0.09s
Running `target/debug/learning-05 'https://z201.vip' z201.md`
args ["target/debug/learning-05", "https://z201.vip", "z201.md"]
url https://z201.vip output z201.md
Converting html to markdown...
Converted markdown has been saved in z201.md.
版本二
- 换一种方式来处理参数
- 打包测试
增加依赖
reqwest = { version = "0.11", features = ["blocking"]}
html2md = "0.2"
structopt = "0.3.13"
- 代码
use std::fs;
use structopt::StructOpt; // 使用StructOpt传递参数
#[derive(StructOpt, Debug)]
struct Cli{
url:String,
output:String,
}
fn main(){
let args = Cli::from_args();
// println!("args {:?} ",args);
let url = &args.url;
let output = &args.output;
println!("url {}\n output {}",url,output);
let body = reqwest::blocking::get(url).unwrap().text().unwrap();
println!("Converting html to markdown...");
let md = html2md::parse_html(&body);
fs::write(output, md.as_bytes()).unwrap();
println!("Converted markdown has been saved in {}.", output);
}
#[test]
fn check() {
println!("test")
}
打包
cargo build --release
- 慢慢等待
测试下
cd target/release
./learning-05 https://z201.vip z201.md
url https://z201.vip
output z201.md
Converting html to markdown...
Converted markdown has been saved in z201.md.