Struct sharp_pencil::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 template_debug: bool,
pub config: Config,
pub extensions: ShareMap,
pub handlebars_registry: Arc<RwLock<Handlebars<'static>>>,
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.
template_debug: bool
Whether live-loading of templates is enabled or not
config: Config
The configuration for this application.
extensions: ShareMap
For storing arbitrary types as “static” data.
handlebars_registry: Arc<RwLock<Handlebars<'static>>>
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
sourceimpl Pencil
impl Pencil
sourcepub fn new(root_path: &str) -> Pencil
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 sharp_pencil::Pencil;
fn main() {
let mut app = Pencil::new("/web/myapp");
}
sourcepub fn is_debug(&self) -> bool
pub fn is_debug(&self) -> bool
The debug flag. This field is configured from the config
with the DEBUG
configuration key. Defaults to False
.
sourcepub fn is_testing(&self) -> bool
pub fn is_testing(&self) -> bool
The testing flag. This field is configured from the config
with the TESTING
configuration key. Defaults to False
.
sourcepub fn set_debug(&mut self, flag: bool)
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.
sourcepub fn set_testing(&mut self, flag: bool)
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.
sourcepub fn set_template_debug(&mut self, flag: bool)
pub fn set_template_debug(&mut self, flag: bool)
Set the template debug flag. This makes the templates live-reload every time they are rendered.
sourcepub fn set_log_level(&self)
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.
sourcepub fn route<M: Into<Matcher>, N: AsRef<[Method]>>(
&mut self,
rule: M,
methods: N,
endpoint: &str,
view_func: ViewFunc
)
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
.
sourcepub fn get<M: Into<Matcher>>(
&mut self,
rule: M,
endpoint: &str,
view_func: ViewFunc
)
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
).
sourcepub fn post<M: Into<Matcher>>(
&mut self,
rule: M,
endpoint: &str,
view_func: ViewFunc
)
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.
sourcepub fn delete<M: Into<Matcher>>(
&mut self,
rule: M,
endpoint: &str,
view_func: ViewFunc
)
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.
sourcepub fn patch<M: Into<Matcher>>(
&mut self,
rule: M,
endpoint: &str,
view_func: ViewFunc
)
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.
sourcepub fn put<M: Into<Matcher>>(
&mut self,
rule: M,
endpoint: &str,
view_func: ViewFunc
)
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.
sourcepub fn add_url_rule(
&mut self,
matcher: Matcher,
methods: &[Method],
endpoint: &str,
view_func: ViewFunc
)
pub fn add_url_rule(
&mut self,
matcher: Matcher,
methods: &[Method],
endpoint: &str,
view_func: ViewFunc
)
Connects a URL rule.
sourcepub fn register_module(&mut self, module: Module)
pub fn register_module(&mut self, module: Module)
Register a module on the application.
sourcepub fn enable_static_file_handling(&mut self)
pub fn enable_static_file_handling(&mut self)
Enables static file handling.
sourcepub fn enable_static_cached_file_handling(&mut self, max_age: Duration)
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.
sourcepub fn before_request<F: Fn(&mut Request<'_, '_, '_>) -> Option<PencilResult> + Send + Sync + 'static>(
&mut self,
f: F
)
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.
sourcepub fn after_request<F: Fn(&Request<'_, '_, '_>, &mut Response) + Send + Sync + 'static>(
&mut self,
f: F
)
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.
sourcepub fn teardown_request<F: Fn(Option<&PencilError>) + Send + Sync + 'static>(
&mut self,
f: F
)
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.
sourcepub fn register_http_error_handler<F: Fn(HTTPError) -> PencilResult + Send + Sync + 'static>(
&mut self,
status_code: u16,
f: F
)
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
.
sourcepub fn register_user_error_handler<F: Fn(UserError) -> PencilResult + Send + Sync + 'static>(
&mut self,
error_desc: &str,
f: F
)
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
.
sourcepub fn httperrorhandler<F: Fn(HTTPError) -> PencilResult + Send + Sync + 'static>(
&mut self,
status_code: u16,
f: F
)
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 sharp_pencil::{Pencil, PencilResult, Response};
use sharp_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);
}
sourcepub fn usererrorhandler<F: Fn(UserError) -> PencilResult + Send + Sync + 'static>(
&mut self,
error_desc: &str,
f: F
)
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 sharp_pencil::Request;
use sharp_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 sharp_pencil::Request;
use sharp_pencil::{Pencil, PencilResult, Response};
use sharp_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);
}
sourcepub fn register_template(&mut self, template_name: &str)
pub fn register_template(&mut self, template_name: &str)
Load and compile and register a template.
sourcepub fn render_template<T: Serialize>(
&self,
template_name: &str,
context: &T
) -> PencilResult
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.
sourcepub fn render_template_string<T: Serialize>(
&self,
source: &str,
context: &T
) -> PencilResult
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.
sourcepub fn handle_request(&self, request: &mut Request<'_, '_, '_>) -> Response
pub fn handle_request(&self, request: &mut Request<'_, '_, '_>) -> Response
The actual application handler.
sourcepub fn run<A: ToSocketAddrs>(self, addr: A)
pub fn run<A: ToSocketAddrs>(self, addr: A)
Runs the application on a hyper HTTP server.
sourcepub fn run_threads<A: ToSocketAddrs>(self, addr: A, threads: usize)
pub fn run_threads<A: ToSocketAddrs>(self, addr: A, threads: usize)
Runs the application on a hyper HTTP server.
Trait Implementations
sourceimpl Handler for Pencil
impl Handler for Pencil
sourcefn handle(&self, req: HTTPRequest<'_, '_>, res: HTTPResponse<'_>)
fn handle(&self, req: HTTPRequest<'_, '_>, res: HTTPResponse<'_>)
Receives a Request
/Response
pair, and should perform some action on them. Read more
sourcefn check_continue(&self, (&Method, &RequestUri, &Headers)) -> StatusCode
fn check_continue(&self, (&Method, &RequestUri, &Headers)) -> StatusCode
Called when a Request includes a Expect: 100-continue
header. Read more
sourcefn on_connection_start(&self)
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
sourcefn on_connection_end(&self)
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
Auto Trait Implementations
impl !RefUnwindSafe for Pencil
impl Send for Pencil
impl Sync for Pencil
impl Unpin for Pencil
impl !UnwindSafe for Pencil
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more