首次提交
This commit is contained in:
27
src/lib.rs
Normal file
27
src/lib.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
mod network;
|
||||
|
||||
#[cxx::bridge]
|
||||
mod ffi {
|
||||
extern "Rust" {
|
||||
fn download_file(url: &str, path: &str) -> Result<()>;
|
||||
|
||||
fn http_get(url: &str) -> Result<String>;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_runtime() -> Runtime {
|
||||
Runtime::new().expect("创建Tokio运行时失败")
|
||||
}
|
||||
|
||||
fn download_file(url: &str, path: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let rt = get_runtime();
|
||||
rt.block_on(network::download_file(url, path))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn http_get(url: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let rt = get_runtime();
|
||||
rt.block_on(network::http_get(url))
|
||||
}
|
||||
62
src/network/mod.rs
Normal file
62
src/network/mod.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use futures_util::StreamExt;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use reqwest::Client;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test() {
|
||||
download_file(
|
||||
"http://114.66.26.35:999/Driver/Key=2Nn77I0E3B9Q4Dy09I5St67Iw1/",
|
||||
"read.bin",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// 从url下载文件
|
||||
pub async fn download_file(url: &str, path: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = Client::new();
|
||||
let response = client.get(url).send().await?;
|
||||
|
||||
// 获取文件总大小(如果服务器提供)
|
||||
let total_size = response.content_length().unwrap_or(0);
|
||||
|
||||
// 创建进度条
|
||||
//let pb = ProgressBar::new(total_size);
|
||||
|
||||
let pb = ProgressBar::with_draw_target(
|
||||
Some(total_size),
|
||||
indicatif::ProgressDrawTarget::stdout_with_hz(20)
|
||||
);
|
||||
|
||||
pb.set_style(
|
||||
ProgressStyle::default_bar()
|
||||
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")?
|
||||
.progress_chars("#>-"),
|
||||
);
|
||||
|
||||
// 创建输出文件
|
||||
let mut file = File::create(path)?;
|
||||
let mut downloaded: u64 = 0;
|
||||
|
||||
// 流式下载
|
||||
let mut stream = response.bytes_stream();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk?;
|
||||
file.write_all(&chunk)?;
|
||||
|
||||
downloaded += chunk.len() as u64;
|
||||
pb.set_position(downloaded);
|
||||
}
|
||||
|
||||
pb.finish_with_message("下载完成");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// http/https请求获取远程数据
|
||||
pub async fn http_get(url: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let client = Client::new();
|
||||
let response = client.get(url).send().await?;
|
||||
Ok(response.text().await?)
|
||||
}
|
||||
Reference in New Issue
Block a user