gpt4 book ai didi

rust - 如何将值发送到 Nickel 中间件函数

转载 作者:行者123 更新时间:2023-11-29 08:22:27 28 4
gpt4 key购买 nike

考虑以下代码:

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")
}

我想在函数登陆中使用数据

最佳答案

镍示例显示 a way to pass a configuration进入服务器对象。

本质上,您使用 with_data 方法实例化一个 Nickel 实例:

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

关于rust - 如何将值发送到 Nickel 中间件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com