PencilFramework是一个Rust的微框架,其灵感来自于Flask。
一个简单应用:
extern crate pencil;use pencil::{Pencil, Request, Response, PencilResult};fn hello(_: &mut Request) -> PencilResult { Ok(Response::from("Hello World!"))}fn main() { let mut app = Pencil::new("/web/hello"); app.get("/", "hello", hello); app.run("127.0.0.1:5000");}路由:
fn user(r: &mut Request) -> PencilResult { let user_id = r.view_args.get("user_id").unwrap(); Ok(format!("user {}", user_id).into())}fn main() { // app here app.get("/user/<int:user_id>", "user", user);}JSON处理:
use std::collections::BTreeMap;use pencil::jsonify;fn app_info(_: &mut Request) -> PencilResult { let mut d = BTreeMap::new(); d.insert("name", "hello"); d.insert("version", "0.1.0"); return jsonify(&d);}fn main() { // app here app.get("/info", "app_info", app_info);}错误处理:
use pencil::HTTPError;fn page_not_found(_: HTTPError) -> PencilResult { let mut response = Response::from("Customized 404 :)"); response.status_code = 404; Ok(response)}fn main() { // app here app.httperrorhandler(404, page_not_found);}
评论