liftinstall/src/http.rs

82 lines
2 KiB
Rust
Raw Normal View History

2018-08-03 11:52:31 +00:00
//! http.rs
//!
//! A simple wrapper around Hyper's HTTP client.
use reqwest::header::CONTENT_LENGTH;
2018-01-30 04:53:28 +00:00
use std::io::Read;
2018-08-07 12:26:53 +00:00
use std::time::Duration;
use reqwest::Client;
2018-10-01 01:27:31 +00:00
/// Asserts that a URL is valid HTTPS, else returns an error.
pub fn assert_ssl(url: &str) -> Result<(), String> {
if url.starts_with("https://") {
Ok(())
} else {
Err(format!("Specified URL was not https"))
}
}
2018-08-07 12:26:53 +00:00
/// 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()
2018-10-01 01:27:31 +00:00
.map_err(|x| format!("Unable to build client: {:?}", x))
2018-08-07 12:26:53 +00:00
}
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-10-01 01:27:31 +00:00
assert_ssl(url)?;
let mut client = build_client()?
.get(url)
.send()
.map_err(|x| format!("Failed to GET resource: {:?}", x))?;
2018-08-07 05:34:57 +00:00
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-10-01 01:27:31 +00:00
assert_ssl(url)?;
let mut client = build_client()?
.get(url)
.send()
.map_err(|x| format!("Failed to GET resource: {:?}", x))?;
2018-01-30 04:53:28 +00:00
let size = match client.headers().get(CONTENT_LENGTH) {
Some(ref v) => v
.to_str()
.map_err(|x| format!("Content length header was invalid: {:?}", x))?
.parse()
.map_err(|x| format!("Failed to parse content length: {:?}", x))?,
None => 0,
2018-01-30 04:53:28 +00:00
};
let mut buf = [0 as u8; 8192];
loop {
let len = client
.read(&mut buf)
.map_err(|x| format!("Failed to read resource: {:?}", x))?;
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(())
}