docs(example): get and save

This commit is contained in:
Paul Campbell 2024-11-09 07:52:42 +00:00
parent dd77e2226e
commit 2edfe7d51f
3 changed files with 89 additions and 3 deletions

View file

@ -15,9 +15,9 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
[dependencies]
derive_more = { version = "1.0", features = [
"from",
"constructor",
"display",
"constructor"
"from"
] }
http = "1.1"
path-clean = "1.0"
@ -28,7 +28,10 @@ tempfile = "3.10"
assert2 = "0.3"
pretty_assertions = "1.4"
test-log = "0.2"
tokio = { version = "1.41", features = ["macros"] }
tokio = { version = "1.41", features = [
"macros",
"rt-multi-thread"
] }
tokio-test = "0.4"
[package.metadata.bin]

82
examples/get.rs Normal file
View file

@ -0,0 +1,82 @@
// 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");
}
}

View file

@ -7,6 +7,7 @@ build:
cargo hack build
cargo hack test
cargo doc
cargo test --example get
install-hooks:
@echo "Installing git hooks"