在这个章节中,会继续介绍 Rocket 对不同数据格式提供的回应支持,包括 JSON 和 MessagePack 格式的回应,以及 Handlebars 和 Tera 这两个 HTML 模板引擎。此外还会介绍 Rocket 框架本身提供的「快闪消息」(Flash Message)机制。

JSON

在之前的章节中有提到 rocket 的 json 特色提供的 serde::json::Json 结构体可以作为路由处理程序的函数的回传值类型,所以该怎么样才能创建一个 serde::json::Json 结构实体呢?

我们可以替自己实作出来的类型加上 Serialize 这个 derive 属性的参数,使这个类型的数据可以直接被 Rocket 框架串行化。使用 serde::json::Json 结构体来包裹可被 Rocket 框架串行化的数据类型,就可以将包裹的数据串行化成 JSON 格式的字符串了!

例如:

#[macro_use]
extern crate serde;

#[macro_use]
extern crate rocket;

use rocket::serde::json::Json;

#[derive(Serialize)]
struct User {
    id:   i32,
    name: String,
}

#[get("/david")]
fn handler() -> Json<User> {
    Json(User {
        id: 5, name: "David".to_string()
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![handler])
}

当路由处理程序的函数是回传 serde::json::Json 时,HTTP 回应中的标头字段除了之前提到的六个基本字段外,还会多出 Content-Type 字段,且该字段的值会被设置为 application/json。

MessagePack

在之前的章节中有提到 rocket 的 msgpack 特色提供的 serde::msgpack::MsgPack 结构体可以作为路由处理程序的函数的回传值类型,所以该怎么样才能创建一个 serde::msgpack::MsgPack 结构实体呢?

我们可以替自己实作出来的类型加上 Serialize 这个 derive 属性的参数,使这个类型的数据可以直接被 Rocket 框架串行化。使用 serde::msgpack::MsgPack 结构体来包裹可被 Rocket 框架串行化的数据类型,就可以将包裹的数据串行化成 MessagePack 格式的数据了!

例如:

#[macro_use]
extern crate serde;

#[macro_use]
extern crate rocket;

use rocket::serde::msgpack::MsgPack;

#[derive(Serialize)]
struct User {
    id:   i32,
    name: String,
}

#[get("/david")]
fn handler() -> MsgPack<User> {
    MsgPack(User {
        id: 5, name: "David".to_string()
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![handler])
}

当路由处理程序的函数是回传 serde::msgpack::MsgPack 时,HTTP 回应中的标头字段除了之前提到的六个基本字段外,还会多出 Content-Type 字段,且该字段的值会被设置为 application/msgpack。

模板引擎

模板引擎可以在原本文档的语法基础上加上更强大的服务器处理功能,来产生出最终的文档。在 Rocket 框架中若要使用模板引擎,可以使用官方另外提供的 rocket_dyn_templates 这个 crate。rocket_dyn_templates 支持 Handlebars 和 Tera 这两种 HTML 模板引擎,前者被广泛用于 JavaScript 生态圈;后者则是参考了在 Python 生态圈中被广泛使用的 Jinja2,再运用 Rust 编程语言所重新开发出来的 HTML 模板引擎,性能会更胜前者。

Handlebars 的官方网站:

Tera 的官方网站:

在 Cargo 程序项目的设置档中引用 rocket_dyn_templates,并依照自己要使用哪种模板引擎,来决定要激活什么特色,如下:

rocket_dyn_templates = { version = "0.1.0", features = ["handlebars", "tera"] }

透过 rocket_dyn_templates 来套用 Handlebars 和 Tera 的模板时,只需要使用一种抽象的 rocket_dyn_templates::Template 结构体来操作即可。

模板引擎的整流片(Fairing)

要在 Rocket 中使用 rocket_dyn_templates::Template 结构体,需要先使用 rocket_dyn_templates::Template 结构体的 fairing 关联函数来取得必要的整流片,并注册给 Rocket 来使用。

程序如下:

use rocket_dyn_templates::Template;

...

rocket::build().attach(Template::fairing())

...

这个整流片会在 Ignite 事件发生时,去解析 Rocket 应用程序根目录底下的 templates 目录中的模板文件。Handlebars 的模板文件使用的扩展名为 .hbs,Tera 的模板文件使用的扩展名为 .tera,如果同时使用相同文件名称(例如:index.html.hbs 和 index.html.tera)的 Handlebars 和 Tera 模板文件,在这个解析的过程中就会被检查出来,而使 Rocket 出现警告消息。如果要改使用别的目录存放 HTML 模板文件,可以在 Rocket 框架的组态配置中添加 template_dir 项目来设置。

在不使用 Release 模式来编译程序项目的情况下,这个整流片还会去监听 Request 事件,在每次接收到 HTTP 请求时都会去检查 templates 目录中的 HTML 模板文件有无改变,如果有的话就重新解析。如此一来,在开发 HTML 模板时,即便不重启 Rocket 应用程序也可以直接套用新的模板变更,方便开发者直接在网页浏览器上刷新页面。

如果需要针对模板引擎来进行设置的话,在取得整流片时,应使用 rocket_dyn_templates::Template 结构体的 custom 关联函数来客制出自己的整流片。

例如以下程序,可以让 Handlebars 模板能够使用我们自己制作好的帮手(Helper)。

#[macro_use]
extern crate handlebars;

#[macro_use]
extern crate rocket;

use rocket_dyn_templates::Template;

...

rocket::build().attach(Template::custom(|engines| {
    handlebars_helper!(inc: |x: i64| x + 1);
    handlebars_helper!(dec: |x: i64| x - 1);
    handlebars_helper!(eq_str: |x: str, y: str| x == y);
    handlebars_helper!(ne_str: |x: str, y: str| x != y);

    engines.handlebars.register_helper("inc", Box::new(inc));
    engines.handlebars.register_helper("dec", Box::new(dec));
    engines.handlebars.register_helper("eq_str", Box::new(eq_str));
    engines.handlebars.register_helper("ne_str", Box::new(ne_str));
}))

...

注意以上程序中的 handlebars_helper! 宏是由 handlebars 这个 crate 提供的哦!记得也要将它给引用至程序项目中。

用模板引擎来产生 HTML 类型的 HTTP 回应

要将 rocket_dyn_templates::Template 结构体作为路由处理程序函数的回传值类型,程序写法如下:

#[macro_use]
extern crate rocket;

use std::collections::HashMap;

use rocket_dyn_templates::Template;

#[get("/")]
fn index() -> Template {
    let context: HashMap<String, String> = HashMap::new();

    Template::render("index", context)
}

#[launch]
fn rocket() -> _ {
    rocket::build().attach(Template::fairing()).mount("/", routes![index])
}

利用 rocket_dyn_templates::Template 结构体提供的 render 关联函数,我们可以指定一个位于 Rocket 应用程序根目录底下的 templates 目录中的 HTML 模板文件的文件相对路径(不含扩展名),以及要用来进行模板填空或是流程控制的「上下文」(context)。这个「上下文」必须要可以被 Rocket 串行化(换句话说就是必须实作 serde 框架的 Serialize 特性)。

当路由处理程序的函数是回传 rocket_dyn_templates::Template 时,HTTP 回应中的标头字段除了之前提到的六个基本字段外,还会多出 Content-Type 字段,且该字段的值会根据次扩展名来设置,例如 .html.hbs 就会被设置为 text/html; charset=utf-8。若没有次扩展名,则预设的 Content-Type 字段为 text/plain; charset=utf-8。

传给 rocket_dyn_templates::Template 结构体提供的 render 关联函数所使用的「上下文」实体也可以用 rocket_dyn_templates 的 context! 宏来快速创建。如以下程序:

#[macro_use]
extern crate rocket;

use rocket_dyn_templates::{context, Template};

#[get("/")]
fn index() -> Template {
    Template::render("index", context! {
        foo: "bar"
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build().attach(Template::fairing()).mount("/", routes![index])
}

快闪消息(Flash Message)

快闪消息是 Rocket 框架提供的一种利用 Cookie 来进行一次性消息传递的机制。什么时候我们会用到「一次性消息」呢?例如会员的网页后台系统,在会员登录前,只能让他们看到登录表单而无法进入会员的网页后台,登录表单必须要填入正确的帐号密码才可以登录,如果登录失败,就会显示错误消息;如果登录成功,就在会员后台显示欢迎消息。上述所提到的「显示错误消息」和「显示欢迎消息」,都属于「一次性消息」,需要在刷新页面后使消息消失。

当我们想透过后端来发送一次性消息给前端时,就可以利用 Rocket 的快闪消息机制,先将要显示的一次性消息从服务器端设置进客户端的 Cookie 中,当客户端取得某个特定的网页时,服务器端就会去查看客户端传来的 Cookie 中是否有预期会有的一次性消息,如果有的话就读取出来,并顺便把该 Cookie 记录删除掉。

例如以下程序,简单模拟出了拥有快闪消息机制的登录页面和后台页面:

#[macro_use]
extern crate rocket;

use std::collections::HashMap;

use rocket::{
    form::Form,
    http::{Cookie, CookieJar},
    request::FlashMessage,
    response::{Flash, Redirect},
};
use rocket_dyn_templates::Template;

#[derive(FromForm)]
struct LoginPostModel {
    password: String,
}

#[get("/login")]
fn login(flash: Option<FlashMessage>) -> Template {
    let mut context: HashMap<&str, &str> = HashMap::new();

    if let Some(flash) = flash.as_ref() {
        context.insert("invalid_message", flash.message());
    }

    Template::render("login", &context)
}

#[post("/login", data = "<model>")]
fn login_action(model: Form<LoginPostModel>, cookies: &CookieJar) -> Flash<Redirect> {
    let pass = model.password == "1234";

    if pass {
        cookies.add_private(Cookie::new("login", "true"));

        Flash::success(Redirect::to(uri!(index())), "Welcome!")
    } else {
        Flash::error(Redirect::to(uri!(login())), "Invalid Password")
    }
}

#[get("/")]
fn index(flash: Option<FlashMessage>, cookies: &CookieJar) -> Result<Template, Box<Redirect>> {
    let has_auth =
        cookies.get_private("login").map(|cookie| cookie.value().eq("true")).unwrap_or(false);

    if has_auth {
        let mut context: HashMap<&str, &str> = HashMap::new();

        if let Some(flash) = flash.as_ref() {
            context.insert("welcome_message", flash.message());
        }

        Ok(Template::render("index", &context))
    } else {
        Err(Box::new(Redirect::to(uri!(login()))))
    }
}

#[launch]
fn rocket() -> _ {
    rocket::build().attach(Template::fairing()).mount("/", routes![login, login_action, index])
}

request::FlashMessage 结构体可以当作请求守卫来使用,而 request::FlashMessage 结构实体的 message 方法可以用来取得消息内容并且顺便将其从 Cookie 中删除。

response::Flash 结构体可以作为路由处理程序的函数的回传值类型,用来将消息存入客户端的 Cookie 中。要创建出 response::Flash 结构实体,可以使用 response::Flash 结构体的 new 关联函数,这个函数必须要手动替消息设置一个「名称」(name),这个名称可以使用 request::FlashMessage 结构实体的 kind 方法来取得。不管 request::FlashMessage 结构实体是只使用到 kind 方法或是 message 方法,还是两个都有用,消息都会从 Cookie 中被删除。如果不想自己设置消息的名称,可以使用 response::Flash 结构体的 success、warning 或 error 关联函数来产生已套用了预设的名称的消息,预设的名称即分别为 success、warning 或 error。

而以下是 index 和 login 这两个 HTML 模板的内容,可以参考看看。

<!DOCTYPE html>
<html>
    <head>
        <meta charset=UTF-8>
        <title>Admin</title>
    </head>
    <body>
        {{#if welcome_message}}
            <p>{{welcome_message}}</p>
        {{/if}}
        <p>Hello, old friend!</p>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset=UTF-8>
        <title>Login</title>
    </head>
    <body>
        <form action="/login" method="POST">
            <input type="password" name="password" placeholder="Input your password">
            <button type="submit">Login</button>
        </form>
        {{#if invalid_message}}
            <p>{{invalid_message}}</p>
        {{/if}}
    </body>
</html>

总结

这个章节介绍了 Rocket 对不同数据格式提供的回应支持,以及 Rocket 框架提供的快闪消息机制。下一个章节要来让我们的 Rocket 能够搭配数据库来使用!

下一章:数据库的访问。