微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pencil Framework Rust​ 的微框架

程序名称:Pencil Framework

授权协议: BSD

操作系统: 跨平台

开发语言: Rust

Pencil Framework 介绍

Pencil Framework 是一个 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);
}

Pencil Framework 官网

https://github.com/fengsp/pencil

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐