如何将值发送到Nickel Middleware函数

时间:2016-10-18 23:07:05

标签: rust nickel

包含以下代码:

extern crate nickel;
use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};

fn main() {
    let data = "wanted";
    let mut server = Nickel::new();
    server.get("/", landing);
    server.listen("localhost:6767");
}

fn landing<'a>(_: &mut Request, response: Response<'a>) -> MiddlewareResult<'a> {
    response.send("not wanted")
}

我想在函数data中使用landing

1 个答案:

答案 0 :(得分:6)

Nickel示例在服务器对象中显示a way to pass a configuration

基本上,您使用Nickel方法实例化with_data实例:

struct MyConfig {
    greet: String,
}

let my_config = MyConfig { greet: "hello".to_string() };

let mut server = Nickel::with_data(my_config);

您的处理程序可以通过server_data方法访问它:

let my_config = req.server_data();
res.send(&*my_config.greet);

因此,将其应用于您的特定示例..您的代码变为:

extern crate nickel;
use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};

fn main() {
    let data = "wanted";
    let mut server = Nickel::with_data(data);
    server.get("/", landing);
    server.listen("localhost:6767");
}

fn landing<'a, 'mw>(request: &mut Request<&'a str>, response: Response<'mw, &'a str>) -> MiddlewareResult<'mw, &'a str> {
    response.send(*request.server_data())
}

导致:

Nickel