Creating a Phoronix CLI Front-End Library
homepage.rs
Now we can go a step further and separate the open_phoronix() and open_testing() functions from main.rs into it's own library, homepage.rs. The open_phoronix() function shall be renamed as online() while open_testing() will be named offline(). That way, the code may be called conveniently with homepage::online() or homepage::offline(). At the same time, to remove any compiler warnings about our online() or offline() functions being unused, tag the functions with #[allow(dead_code)].
use hyper::Client;
use hyper::header::Connection;
use std::io::Read;
#[allow(dead_code)]
pub fn online() -> String {
let client = Client::new();
let mut response = client.get("https://www.phoronix.com/").
header(Connection::close()).send().unwrap();
let mut body = String::new();
response.read_to_string(&mut body).unwrap();
return body;
}
#[allow(dead_code)]
pub fn offline() -> &'static str { include_str!("phoronix.html") }
phoronix_cli.rs
Now it might be a good idea to separate the printing code from main.rs into our new phoronix_cli.rs front-end. Let's call this new function print() so that we can later call this in main() with phoronix_cli::print(). Because we now need to get our homepage string from the homepage.rs file, we need to make that change too.
use article::Article;
use homepage;
pub fn print() {
let phoronix_articles = Article::get_articles(homepage::offline());
for article in phoronix_articles.iter().rev() {
println!("Title: {}", article.title);
println!("Link: https://www.phoronix.com/{}", article.link);
println!("Details: {}", article.details);
println!("Summary: {}\n", article.summary);
}
}
When you are finished with the program, make sure to make the correct changes in main.rs to reflect the newly-created libs. We will simply add mod homepage and mod phoronix_cli to the mod list and call our print() function in phoronix_cli with phoronix_cli::print().
main.rs
Now our main.rs file should look like such:
extern crate hyper;
extern crate select;
mod article;
mod homepage;
mod phoronix_cli;
fn main() {
phoronix_cli::print();
}
Run cargo run again to make sure it still builds and runs.