extract serving code to a separate module

This commit is contained in:
Michal Budzynski 2017-06-14 14:43:43 +02:00
parent f889eb3d12
commit 79cdcb46de
1 changed files with 73 additions and 70 deletions

View File

@ -13,17 +13,6 @@ extern crate time;
#[cfg(feature = "watch")]
extern crate crossbeam;
// Dependencies for the Serve feature
#[cfg(feature = "serve")]
extern crate iron;
#[cfg(feature = "serve")]
extern crate staticfile;
#[cfg(feature = "serve")]
extern crate ws;
#[cfg(feature = "serve")]
use iron::{Iron, AfterMiddleware, IronResult, IronError, Request, Response, status, Set, Chain};
use std::env;
use std::error::Error;
use std::ffi::OsStr;
@ -96,7 +85,7 @@ fn main() {
#[cfg(feature = "watch")]
("watch", Some(sub_matches)) => watch(sub_matches),
#[cfg(feature = "serve")]
("serve", Some(sub_matches)) => serve(sub_matches),
("serve", Some(sub_matches)) => serve::serve(sub_matches),
("test", Some(sub_matches)) => test(sub_matches),
(_, _) => unreachable!(),
};
@ -237,28 +226,41 @@ fn watch(args: &ArgMatches) -> Result<(), Box<Error>> {
}
#[cfg(feature = "serve")]
mod serve {
extern crate iron;
extern crate staticfile;
extern crate ws;
use std;
use std::path::Path;
use std::error::Error;
use self::iron::{Iron, AfterMiddleware, IronResult, IronError, Request, Response, status, Set, Chain};
use clap::ArgMatches;
use mdbook::MDBook;
use {get_book_dir, open, trigger_on_change};
struct ErrorRecover;
#[cfg(feature = "serve")]
impl AfterMiddleware for ErrorRecover {
fn catch(&self, _: &mut Request, err: IronError) -> IronResult<Response> {
match err.response.status {
// each error will result in 404 response
Some(_) => Ok(err.response.set(status::NotFound)),
_ => Err(err)
_ => Err(err),
}
}
}
// Watch command implementation
#[cfg(feature = "serve")]
fn serve(args: &ArgMatches) -> Result<(), Box<Error>> {
pub fn serve(args: &ArgMatches) -> Result<(), Box<Error>> {
const RELOAD_COMMAND: &'static str = "reload";
let book_dir = get_book_dir(args);
let book = MDBook::new(&book_dir).read_config()?;
let mut book = match args.value_of("dest-dir") {
Some(dest_dir) => book.with_destination(dest_dir),
Some(dest_dir) => book.with_destination(Path::new(dest_dir)),
None => book,
};
@ -301,7 +303,8 @@ fn serve(args: &ArgMatches) -> Result<(), Box<Error>> {
book.build()?;
let mut chain = Chain::new(staticfile::Static::new(book.get_destination().expect("destination is present, checked before")));
let mut chain = Chain::new(staticfile::Static::new(book.get_destination()
.expect("destination is present, checked before")));
chain.link_after(ErrorRecover);
let _iron = Iron::new(chain).http(&*address).unwrap();
@ -329,7 +332,7 @@ fn serve(args: &ArgMatches) -> Result<(), Box<Error>> {
Ok(())
}
}
fn test(args: &ArgMatches) -> Result<(), Box<Error>> {
let book_dir = get_book_dir(args);