kxio/examples/get.rs
Paul Campbell 02adc7dcd2
All checks were successful
Rust / build (map[name:nightly]) (push) Successful in 1m52s
Rust / build (map[name:stable]) (push) Successful in 3m52s
Release Please / Release-plz (push) Successful in 39s
docs(example): get and save
2024-11-09 15:42:53 +00:00

82 lines
2.1 KiB
Rust

// example to show fetching a URL and saving to a file
use std::path::Path;
#[tokio::main]
async fn main() -> kxio::Result<()> {
let net = kxio::net::new();
let fs = kxio::fs::temp()?;
let url = "https://git.kemitix.net/kemitix/kxio/raw/branch/main/README.md";
let file_path = fs.base().join("README.md");
download_and_save(url, &file_path, &fs, &net).await?;
print_file(&file_path, &fs)?;
Ok(())
}
async fn download_and_save(
url: &str,
file_path: &Path,
fs: &kxio::fs::FileSystem,
net: &kxio::net::Net,
) -> kxio::Result<()> {
println!("fetching: {url}");
let request = net.client().get(url);
let response = net.send(request).await?;
let body = response.text().await?;
println!("fetched {} bytes", body.bytes().len());
println!("writing file: {}", file_path.display());
let file = fs.file(file_path);
file.write(body)?;
Ok(())
}
fn print_file(file_path: &Path, fs: &kxio::fs::FileSystem) -> kxio::Result<()> {
println!("reading file: {}", file_path.display());
let file = fs.file(file_path);
let reader = file.reader()?;
let contents = reader.as_str();
println!("{contents}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn should_save_remote_body() {
//given
let net = kxio::net::mock();
let url = "http://localhost:8080";
net.on(net.client().get(url).build().expect("request"))
.respond(
net.response()
.body("contents")
.expect("response body")
.into(),
)
.expect("mock");
let fs = kxio::fs::temp().expect("temp fs");
let file_path = fs.base().join("foo");
//when
download_and_save(url, &file_path, &fs, &net.into())
.await
.expect("system under test");
//then
let file = fs.file(&file_path);
let reader = file.reader().expect("reader");
let contents = reader.as_str();
assert_eq!(contents, "contents");
}
}