Struct pencil::Pencil [] [src]

pub struct Pencil {
    pub root_path: String,
    pub name: String,
    pub static_folder: String,
    pub static_url_path: String,
    pub template_folder: String,
    pub config: Config,
    pub handlebars_registry: RwLock<Box<Handlebars>>,
    pub url_map: Map,
    pub modules: HashMap<StringModule>,
    // some fields omitted
}

The pencil type. It acts as the central application object. Once it is created it will act as a central registry for the view functions, the URL rules and much more.

Fields

root_path: String

The path where your application locates.

name: String

The name of the application. By default it's guessed from the root path.

static_folder: String

The folder with static files that should be served at static_url_path. Defaults to the "static" folder in the root path of the application.

static_url_path: String

The url path for the static files on the web, defaults to be "/static".

template_folder: String

The folder that contains the templates that should be used for the application. Defaults to ''templates'' folder in the root path of the application.

config: Config

The configuration for this application.

handlebars_registry: RwLock<Box<Handlebars>>

The Handlebars registry used to load templates and register helpers.

url_map: Map

The url map for this pencil application.

modules: HashMap<StringModule>

All the attached modules in a hashmap by name.

Methods

impl Pencil
[src]

fn new(root_path: &str) -> Pencil

Create a new pencil object. It is passed the root path of your application. The root path is used to resolve resources from inside it, for more information about resource loading, see method open_resource.

Usually you create a pencil object in your main function like this:

use pencil::Pencil;

fn main() {
    let mut app = Pencil::new("/web/myapp");
}

fn is_debug(&self) -> bool

The debug flag. This field is configured from the config with the DEBUG configuration key. Defaults to False.

fn is_testing(&self) -> bool

The testing flag. This field is configured from the config with the TESTING configuration key. Defaults to False.

fn set_debug(&mut self, flag: bool)

Set the debug flag. This field is configured from the config with the DEBUG configuration key. Set this to True to enable debugging of the application.

fn set_testing(&mut self, flag: bool)

Set the testing flag. This field is configured from the config with the TESTING configuration key. Set this to True to enable the test mode of the application.

fn set_log_level(&self)

Set global log level based on the application's debug flag. This is only useful for env_logger crate users. On debug mode, this turns on all debug logging.

fn route<M: Into<Matcher>, N: AsRef<[Method]>>(&mut self, rule: M, methods: N, endpoint: &str, view_func: ViewFunc)

This is used to register a view function for a given URL rule. Basically this example:

app.route("/home", &[Get], "home", home);
app.route("/user/<user_id:int>", &[Get], "user", user);

A rule that listens for GET will implicitly listen for HEAD.

fn get<M: Into<Matcher>>(&mut self, rule: M, endpoint: &str, view_func: ViewFunc)

This is a shortcut for route, register a view function for a given URL rule with just GET method (implicitly HEAD).

fn post<M: Into<Matcher>>(&mut self, rule: M, endpoint: &str, view_func: ViewFunc)

This is a shortcut for route, register a view function for a given URL rule with just POST method.

fn delete<M: Into<Matcher>>(&mut self, rule: M, endpoint: &str, view_func: ViewFunc)

This is a shortcut for route, register a view function for a given URL rule with just DELETE method.

fn patch<M: Into<Matcher>>(&mut self, rule: M, endpoint: &str, view_func: ViewFunc)

This is a shortcut for route, register a view function for a given URL rule with just PATCH method.

fn put<M: Into<Matcher>>(&mut self, rule: M, endpoint: &str, view_func: ViewFunc)

This is a shortcut for route, register a view function for a given URL rule with just PUT method.

fn add_url_rule(&mut self, matcher: Matcher, methods: &[Method], endpoint: &str, view_func: ViewFunc)

Connects a URL rule.

fn register_module(&mut self, module: Module)

Register a module on the application.

fn enable_static_file_handling(&mut self)

Enables static file handling.

fn before_request(&mut self, f: BeforeRequestFunc)

Registers a function to run before each request.

fn after_request(&mut self, f: AfterRequestFunc)

Registers a function to run after each request. Your function must take a response object and modify it.

fn teardown_request(&mut self, f: TeardownRequestFunc)

Registers a function to run at the end of each request, regardless of whether there was an error or not.

fn register_http_error_handler(&mut self, status_code: u16, f: HTTPErrorHandler)

Registers a function as one http error handler. Same to httperrorhandler.

fn register_user_error_handler(&mut self, error_desc: &str, f: UserErrorHandler)

Registers a function as one user error handler. Same to usererrorhandler.

fn httperrorhandler(&mut self, status_code: u16, f: HTTPErrorHandler)

Registers a function as one http error handler. Example:

use pencil::{Pencil, PencilResult, Response};
use pencil::HTTPError;


fn page_not_found(error: HTTPError) -> PencilResult {
    let mut response = Response::from("The page does not exist");
    response.status_code = 404;
    return Ok(response);
}


fn main() {
    let mut app = Pencil::new("/web/demo");
    app.httperrorhandler(404, page_not_found);
}

fn usererrorhandler(&mut self, error_desc: &str, f: UserErrorHandler)

Registers a function as one user error handler. There are two ways to handle user errors currently, you can do it in your own view like this:

use pencil::Request;
use pencil::{PencilResult, Response};


#[derive(Clone, Copy)]
struct MyErr(isize);


fn some_operation() -> Result<isize, MyErr> {
    return Err(MyErr(10));
}


fn my_err_handler(_: MyErr) -> PencilResult {
    Ok(Response::from("My err occurred!"))
}


fn hello(_: &mut Request) -> PencilResult {
    match some_operation() {
        Ok(_) => Ok(Response::from("Hello!")),
        Err(e) => my_err_handler(e),
    }
}

The problem with this is that you have to do it in all of your views, it brings a lot of redundance, so pencil provides another solution, currently I still haven't got any better idea on how to store user error handlers, this feature is really just experimental, if you have any good idea, please wake me up. Here is one simple example:

use std::convert;

use pencil::Request;
use pencil::{Pencil, PencilResult, Response};
use pencil::{PencilError, PenUserError, UserError};


#[derive(Clone, Copy)]
pub struct MyErr(isize);

impl convert::From<MyErr> for PencilError {
    fn from(err: MyErr) -> PencilError {
        let user_error = UserError::new("MyErr");
        return PenUserError(user_error);
    }
}


fn my_err_handler(_: UserError) -> PencilResult {
    Ok(Response::from("My err occurred!"))
}


fn some_operation() -> Result<String, MyErr> {
    return Err(MyErr(10));
}


fn hello(_: &mut Request) -> PencilResult {
    let rv = try!(some_operation());
    return Ok(rv.into());
}


fn main() {
    let mut app = Pencil::new("/web/demo");
    // Use error description as key to store handlers, really ugly...
    app.usererrorhandler("MyErr", my_err_handler);
}

fn register_template(&mut self, template_name: &str)

Load and compile and register a template.

fn render_template<T: ToJson>(&self, template_name: &str, context: &T) -> PencilResult

We use handlebars-rs as template engine. Renders a template from the template folder with the given context. The template name is the name of the template to be rendered. The context is the variables that should be available in the template.

fn render_template_string<T: ToJson>(&self, source: &str, context: &T) -> PencilResult

We use handlebars-rs as template engine. Renders a template from the given template source string with the given context. The source is the sourcecode of the template to be rendered. The context is the variables that should be available in the template.

fn handle_request(&self, request: &mut Request) -> Response

The actual application handler.

fn run<A: ToSocketAddrs>(self, addr: A)

Runs the application on a hyper HTTP server.

Trait Implementations

impl Handler for Pencil
[src]

fn handle(&self, req: HTTPRequest, res: HTTPResponse)

Receives a Request/Response pair, and should perform some action on them. Read more

fn check_continue(&self, (&Method, &RequestUri, &Headers)) -> StatusCode

Called when a Request includes a Expect: 100-continue header. Read more

fn on_connection_start(&self)

This is run after a connection is received, on a per-connection basis (not a per-request basis, as a connection with keep-alive may handle multiple requests) Read more

fn on_connection_end(&self)

This is run before a connection is closed, on a per-connection basis (not a per-request basis, as a connection with keep-alive may handle multiple requests) Read more

impl PathBound for Pencil
[src]

fn open_resource(&self, resource: &str) -> File

Opens a resource from the root path folder. Consider the following folder structure: Read more

impl Display for Pencil
[src]

fn fmt(&self, f: &mut Formatter) -> Result

Formats the value using the given formatter.

impl Debug for Pencil
[src]

fn fmt(&self, f: &mut Formatter) -> Result

Formats the value using the given formatter.