Consdier the following code:
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")
}
I want to use data
in the function landing
.
The Nickel examples show a way to pass a configuration into the server object.
Essentially, you instantiate a Nickel
instance using its with_data
method:
struct MyConfig {
greet: String,
}
let my_config = MyConfig { greet: "hello".to_string() };
let mut server = Nickel::with_data(my_config);
And your handler can access it via the server_data
method:
let my_config = req.server_data();
res.send(&*my_config.greet);
So, applying that to your specific example.. your code becomes:
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())
}
Resulting in: