- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在下面实现了一个示例代理服务器,但尝试尝试一下,可能无法弄清楚如何将client
从封闭中取出,以便可以共享它。如果我将其取出并删除move
,则它将无法编译,因为闭包可能会超过client
的生命周期。如果我继续前进,那就是FnOnce
而不是Fn
。我如何举起client
以便可以共享并延长其生存期,以便编译器意识到它一直存在直到应用程序终止?
cargo.toml
[dependencies]
tokio = { version = "0.2", features = ["full"] }
reqwest = { version = "0.10", features = ["json"] }
warp = "0.2.5"
env_logger = "0.8.2"
serde_json = "1.0.61"
futures = "0.3.8"
主
use serde_json::Value;
use std::collections::HashMap;
use warp::{Filter, http::Method};
#[tokio::main]
async fn main() {
env_logger::init();
let log = warp::log("webserver::proxy");
let cors = warp::cors()
.allow_any_origin()
.allow_header("content-type")
.allow_methods(&[Method::GET, Method::POST, Method::DELETE]);
let signup_route = warp::post()
.and(warp::path("signup"))
.and(warp::path::end())
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::json())
.and_then(|body: HashMap<String, Value>| async move {
// How do I move token and client out of this closure to share it?
let token = std::env::var_os("TOKEN").unwrap().into_string().unwrap();
let client = reqwest::Client::new();
return match client.post("https://api.example.com/api")
.header("Authorization", &token)
.header("Content-Type", "application/json")
.json(&body)
.send().await {
Ok(x) => {
let status = x.status();
let json = x.json::<HashMap<String, Value>>().await;
return match json {
Ok(j) => Ok(warp::reply::with_status(warp::reply::json(&j), status)),
Err(_) => Err(warp::reject()),
}
},
Err(_) => Err(warp::reject()),
};
});
let option_route = warp::options().map(warp::reply);
let routes = signup_route.or(option_route).with(cors).with(log);
warp::serve(routes)
.run(([127, 0, 0, 1], 3030))
.await;
}
最佳答案
您需要将客户端和 token 发送到warp
,后者将它们运送到不同的线程中(就编译器而言),这些线程可能会超过保存它们的值。这就是为什么编译器不允许闭包捕获对在其外部定义的client
和token
的引用。
相反,您需要对这些值进行堆分配,然后将reference-counted smart pointer移至闭包中。这样就可以吃蛋糕了:您拥有一个拥有值的move
闭包,拥有的“值”只是一个指针,并且拥有该指针的另一个副本,可通过克隆Arc
获得。必须对内部闭包执行类似的转换,出于相同的原因,该闭包必须变为move
。
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use warp::{http::Method, Filter};
#[tokio::main]
async fn main() {
env_logger::init();
let log = warp::log("webserver::proxy");
let cors = warp::cors()
.allow_any_origin()
.allow_header("content-type")
.allow_methods(&[Method::GET, Method::POST, Method::DELETE]);
let client = Arc::new(reqwest::Client::new());
let client_shared = Arc::clone(&client);
let token = Arc::new(std::env::var_os("TOKEN").unwrap().into_string().unwrap());
let token_shared = Arc::clone(&token);
let signup_route = warp::post()
.and(warp::path("signup"))
.and(warp::path::end())
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::json())
.and_then(move |body: HashMap<String, Value>| {
let client_shared = Arc::clone(&client_shared);
let token_shared = Arc::clone(&token_shared);
async move {
return match client_shared
.post("https://api.example.com/api")
.header("Authorization", token_shared.as_str())
.header("Content-Type", "application/json")
.json(&body)
.send()
.await
{
Ok(x) => {
let status = x.status();
let json = x.json::<HashMap<String, Value>>().await;
return match json {
Ok(j) => Ok(warp::reply::with_status(warp::reply::json(&j), status)),
Err(_) => Err(warp::reject()),
};
}
Err(_) => Err(warp::reject()),
};
}
});
let option_route = warp::options().map(warp::reply);
let routes = signup_route.or(option_route).with(cors).with(log);
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
关于rust - 如何在不变成FnOnce的情况下将共享变量从 rust Fn中删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65767979/
这个问题在这里已经有了答案: JavaScript idiom: !something && function() (5 个答案) 关闭 9 年前。 我多次看到 fn && fn() 是对 if (
我在一个对象中有两个函数 var obj = {}; obj.fn1 = function(){ console.log('obj.fn1'); return this; }; obj.fn2 = f
我正在尝试使用以下 cloudformation 堆栈,但我一直失败并出现以下错误: 模板错误:每个 Fn::Split 对象都需要两个参数,(1) 字符串分隔符和 (2) 要拆分的字符串或返回要拆分
请在这方面提供一些帮助,我将不胜感激。不确定这意味着什么,因为这是我第一次使用 node 和 express。我将 express 设置为与 Node 一起使用,并尝试遵循网站 Express.js
我有一段代码接受 fn 作为参数并将其存储在 object 属性中。 var obj = {}; function anotherFn(fn){ obj["name"] = fn.apply(f
谁能解释一下? IE8 ( function(){ window.foo = function foo(){}; console.log( window.foo === foo );
我查看了lazy-seq的来源,我发现了这个: Clojure 1.4.0 user=> (source lazy-seq) (defmacro lazy-seq "Takes a body of
我知道 $fn.insertAfter() 用于在作为参数提供的元素之后插入元素。 $fn.after() 与它有何不同? 最佳答案 $.fn.after()help在您调用的目标元素之后插入一个元素
所以我的网络模板中有这个 CloudFormation 资源: Resources: ... PubSubnetAz2: Type: AWS::EC2::Subnet
有some conventions说到using brackets in JavaScript ,但是当使用方括号调用时,它们实际上会得到不同的对待吗? fn () 是否与 fn() 有任何不同,人类
我正在尝试将 clojurescript 编译为 Nodejs,我只是想使用 println 函数: (println "hello world") 但是,它给了我一个错误 No *print-fn
我在看别人代码的时候,有看到代码是这样写的 function(){ fn&&fn() } 大概意思是这么个意思,但是这我感觉这样写好像没意义,有带佬能指点一下吗
是否可以使用折叠表达式实现以下目的? template auto foo(Args... args) { //calling foo(x0, x1, x2) should be exactly
fn func(_: i64) -> bool { true } fn func_of_func(callback: &fn(i64) -> bool, arg: i64) -> bool {
我一直在到处寻找对此的解释。我知道,在 Javascript 中,您可以使用方括号表示法获取/设置对象的属性,但是当您在括号中使用“+”时会发生什么,如下所示: obj['e'+type+fn] =
我正在尝试根据Fn::GetAZs'集合动态生成资源: AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::LanguageExtensio
新的 React Hooks 功能很酷,但有时会让我感到困惑。特别是,我将此代码包装在 useEffect Hook 中: const compA = ({ num }) => { const [
我看到这个快捷方式作为代码 Kata 的答案给出,但我很难理解下面的示例在做什么。 function func(fn) { return fn.bind.apply(fn, arguments);
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: C++ namespace question 我见过几个没有命名空间的例子。这样做有什么好处?
所以在一个项目中,我找到了可以简化为的代码: export abstract class Logger { private static log(level: LogLevels, ...ar
我是一名优秀的程序员,十分优秀!