liftinstall/src/http.rs

70 lines
1.7 KiB
Rust
Raw Normal View History

2018-08-03 11:52:31 +00:00
//! http.rs
//!
//! A simple wrapper around Hyper's HTTP client.
2018-01-30 04:53:28 +00:00
use hyper::header::ContentLength;
use std::io::Read;
2018-08-07 12:26:53 +00:00
use std::time::Duration;
use reqwest::Client;
/// Builds a customised HTTP client.
pub fn build_client() -> Result<Client, String> {
Client::builder()
2018-08-09 05:21:50 +00:00
.timeout(Duration::from_secs(8))
2018-08-07 12:26:53 +00:00
.build()
.map_err(|x| format!("Unable to build cient: {:?}", x))
}
2018-01-30 04:53:28 +00:00
2018-08-07 05:34:57 +00:00
/// Downloads a text file from the specified URL.
pub fn download_text(url: &str) -> Result<String, String> {
2018-08-07 12:26:53 +00:00
let mut client = match build_client()?.get(url).send() {
2018-08-07 05:34:57 +00:00
Ok(v) => v,
Err(v) => return Err(format!("Failed to GET resource: {:?}", v)),
};
client
.text()
.map_err(|v| format!("Failed to get text from resource: {:?}", v))
}
2018-01-30 04:53:28 +00:00
/// Streams a file from a HTTP server.
2018-08-04 08:35:00 +00:00
pub fn stream_file<F>(url: &str, mut callback: F) -> Result<(), String>
2018-01-30 04:54:44 +00:00
where
F: FnMut(Vec<u8>, u64) -> (),
2018-01-30 04:54:44 +00:00
{
2018-08-07 12:26:53 +00:00
let mut client = match build_client()?.get(url).send() {
2018-01-30 04:53:28 +00:00
Ok(v) => v,
Err(v) => return Err(format!("Failed to GET resource: {:?}", v)),
};
let size = {
2018-01-30 04:54:44 +00:00
let size: Option<&ContentLength> = client.headers().get();
2018-01-30 04:53:28 +00:00
match size {
Some(&ContentLength(v)) => v,
2018-01-30 04:54:44 +00:00
None => 0,
2018-01-30 04:53:28 +00:00
}
};
let mut buf = [0 as u8; 8192];
loop {
let len = client.read(&mut buf);
let len = match len {
Ok(v) => v,
2018-01-30 04:54:44 +00:00
Err(v) => return Err(format!("Failed to read resource: {:?}", v)),
2018-01-30 04:53:28 +00:00
};
if len == 0 {
break;
}
2018-01-30 04:54:44 +00:00
let buf_copy = &buf[0..len];
2018-01-30 04:53:28 +00:00
let buf_copy = buf_copy.to_vec();
callback(buf_copy, size);
}
Ok(())
}