Skip to main content

htmlpacker/
fetcher.rs

1/*
2* fetcher.rs
3*
4* fetches source files whether they are local or external
5*/
6
7use std::fs::File;
8use std::io::prelude::*;
9use std::path::{Path};
10use std::error::Error;
11// crates
12use url::Url;
13
14
15// go through each external script file
16// saving 
17pub async fn get_external_scripts_text(
18    script_urls: Vec<&str>
19) -> Result<Vec<String>, Box<dyn Error>> {
20    let mut script_strings: Vec<String> = vec![];
21    for url in script_urls {
22        script_strings.push(reqwest::get(url).await?.text().await?);
23    }
24    Ok(script_strings) 
25}
26
27// go through each local script file
28pub fn get_local_scripts_text(
29    script_path_literals: Vec<&str>
30) -> Result<Vec<String>, Box<dyn Error>> {
31    let mut script_strings: Vec<String> = vec![];
32    for path in script_path_literals {
33        script_strings.push(
34            get_local_script(Path::new(path)).unwrap()
35        )
36    }
37    Ok(script_strings)
38}
39
40pub fn get_local_script(path: &Path) -> Result<String, Box<dyn Error>> {
41    let mut file = File::open(path)?;
42    let mut text = String::new();
43    file.read_to_string(&mut text)?;
44    Ok(text)
45}
46
47pub fn get_local_file(path: &Path) -> Result<String, Box<dyn Error>> {
48    let mut file = File::open(path)?;
49    let mut text = String::new();
50    file.read_to_string(&mut text)?;
51    Ok(text)
52}
53
54pub async fn get_remote_file(url: Url) -> Result<String, Box<dyn Error>> {
55    let text = reqwest::get(url).await?.text().await?;
56    Ok(text)
57}
58
59// append each external css file together
60pub async fn get_css_string(
61    css_urls: Vec<&str>
62) -> Result<String, Box<dyn Error>> {
63    let mut css_string = String::from(""); 
64    for url in css_urls {
65        css_string += &reqwest::get(url).await?.text().await?;
66    }
67    Ok(css_string)
68}