Struct Pencil

Source
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 extensions: ShareMap,
    pub handlebars_registry: RwLock<Box<Handlebars>>,
    pub url_map: Map,
    pub modules: HashMap<String, Module>,
    /* private fields */
}
Expand description

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.

§extensions: ShareMap

For storing arbitrary types as “static” data.

§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<String, Module>

All the attached modules in a hashmap by name.

Implementations§

Source§

impl Pencil

Source

pub 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 chilli::Pencil;

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

pub fn is_debug(&self) -> bool

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

Source

pub fn is_testing(&self) -> bool

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

Source

pub 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.

Source

pub 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.

Source

pub 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.

Source

pub 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.

Source

pub 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).

Source

pub 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.

Source

pub 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.

Source

pub 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.

Source

pub 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.

Source

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

Connects a URL rule.

Source

pub fn register_module(&mut self, module: Module)

Register a module on the application.

Source

pub fn enable_static_file_handling(&mut self)

Enables static file handling.

Source

pub fn enable_static_cached_file_handling(&mut self, max_age: Duration)

Enables static file handling with caching. (304 Not Modified + Max-Age) The static files are considered “not modified” since the server was started.

Source

pub fn before_request<F: Fn(&mut Request<'_, '_, '_>) -> Option<PencilResult> + Send + Sync + 'static>( &mut self, f: F, )

Registers a function to run before each request.

Source

pub fn after_request<F: Fn(&Request<'_, '_, '_>, &mut Response) + Send + Sync + 'static>( &mut self, f: F, )

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

Source

pub fn teardown_request<F: Fn(Option<&PencilError>) + Send + Sync + 'static>( &mut self, f: F, )

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

Source

pub fn register_http_error_handler<F: Fn(HTTPError) -> PencilResult + Send + Sync + 'static>( &mut self, status_code: u16, f: F, )

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

Source

pub fn register_user_error_handler<F: Fn(UserError) -> PencilResult + Send + Sync + 'static>( &mut self, error_desc: &str, f: F, )

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

Source

pub fn httperrorhandler<F: Fn(HTTPError) -> PencilResult + Send + Sync + 'static>( &mut self, status_code: u16, f: F, )

Registers a function as one http error handler. Example:

use chilli::{Pencil, PencilResult, Response};
use chilli::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);
}
Source

pub fn usererrorhandler<F: Fn(UserError) -> PencilResult + Send + Sync + 'static>( &mut self, error_desc: &str, f: F, )

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 chilli::Request;
use chilli::{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 chilli::Request;
use chilli::{Pencil, PencilResult, Response};
use chilli::{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);
}
Source

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

Load and compile and register a template.

Source

pub fn render_template<T: Serialize>( &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.

Source

pub fn render_template_string<T: Serialize>( &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.

Source

pub fn handle_request(&self, request: &mut Request<'_, '_, '_>) -> Response

The actual application handler.

Source

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

Runs the application on a hyper HTTP server.

Source

pub fn run_threads<A: ToSocketAddrs>(self, addr: A, threads: usize)

Runs the application on a hyper HTTP server.

Trait Implementations§

Source§

impl Debug for Pencil

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Display for Pencil

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Handler for Pencil

Source§

fn handle(&self, req: HTTPRequest<'_, '_>, res: HTTPResponse<'_>)

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

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

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

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)
Source§

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)
Source§

impl PathBound for Pencil

Source§

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

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

Auto Trait Implementations§

§

impl !Freeze for Pencil

§

impl !RefUnwindSafe for Pencil

§

impl Send for Pencil

§

impl Sync for Pencil

§

impl Unpin for Pencil

§

impl !UnwindSafe for Pencil

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Typeable for T
where T: Any,

Source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
Source§

impl<T> DebugAny for T
where T: Any + Debug,

Source§

impl<T> UnsafeAny for T
where T: Any,