0

考虑以下代码:

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

4

1 回答 1

6

Nickel 示例展示了一种将配置传递到服务器对象的方法。

本质上,您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())
}

导致:

镍

于 2016-10-18T23:32:48.847 回答