我正在使用rust-aws-lambda
项目。我的用例是使用 Lambda 作为 API Gateway Proxy。此外,我正在使用this example中解释的闭包,因为我想在我的 lambda 代码中使用共享资源,如客户端和秘密值(从 AWS Secrets Manager 检索)。
我长期困扰的问题是如何将闭包抽象为另一个 helper 函数。例如,我希望函数在这种情况下返回外部闭包。我已经尝试过,但我无法让 Rust 编译器让我这样做。
这两个闭包都在main
函数中。根据列出的示例,我的内部闭包定义如下:
let handler_func_closure = move |event: ApiProxyRequest| async move {
...
Ok::<_, Error>(success_resp)
};
这些是我在代码中的相关导入:
use lambda_http::{service_fn, Body, Error, IntoResponse, Request as ApiProxyRequest, RequestExt};
use lambda_http::tower::util::ServiceFn;
我有的闭包,我在main.rs
中的 asyncmain
函数中定义,到目前为止为我工作。
let outer_closure = move |event: ApiProxyRequest| async move {
match handler_func_closure(event).await {
Ok(s) => Ok(s.into_response()),
Err(e) => Ok(http::Response::builder()
.header(http::header::CONTENT_TYPE, "application/json")
.status(400)
.body(
serde_json::to_string(&json!({"error": &err.to_string()}))
.expect("unable to serialize serde_json::Value")
.into(),
)
.expect("unable to build http::Response")),
}
};
其中into_response()
由从 traitIntoResponse
实现的结构满足。
所以基本上我想要做的是使一个函数返回闭包,可以传递给service_fn
。
pub fn get_service_fn<T, T2, F, F2, I: IntoResponse>(handler_func_closure: T) -> ServiceFn<T2>
where T: Fn(http::Request<Body>) -> F + Send + Sync,
T2: Fn(lambda_http::Request) -> F2,
F2: Future<Output=crate::Result<http::Response<Body>>>,
F: Future<Output=crate::Result<I>> + Send {
let outer_closure = move |event: ApiProxyRequest| async move {
match handler_func_closure(event).await {
Ok(s) => Ok(s.into_response()),
Err(e) => failure(Box::new(e), None),
}
};
service_fn(outer_closure)
};
我很想知道是否有人能够得到这个工作,其中一个函数返回的外部闭包可以传递给service_fn
。
我觉得我花了无数的时间试图弄清楚这一点,但我一直无法使它工作。我不完全确定这是否可能在 Rust 中说实话,但我会很好奇,如果有人有一个想法如何处理这个。
编辑:这是我得到的情况下,它是有帮助的编译器错误:
error[E0308]: mismatched types
--> src/bin/my_lambda/main.rs:197:16
|
185 | pub fn get_service_fn<T, T2, F, F2, I: IntoResponse>(handler_func_closure: T) -> ServiceFn<T2>
| -- this type parameter
...
190 | let outer_closure = move |event: ApiProxyRequest| async move {
| __________________________-________________________________________-
| | _________________________|
| ||
191 | || match handler_func_closure(event).await {
192 | || Ok(s) => Ok(s.into_response()),
193 | || Err(e) => failure(Box::new(e), None),
194 | || }
195 | || };
| || -
| ||_____|
| |______the found closure
| the found `async` block
196 |
197 | service_fn(outer_closure)
| ^^^^^^^^^^^^^ expected type parameter `T2`, found closure
|
::: /Users/rnag/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/future/mod.rs:61:43
|
61 | pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
| ------------------------------- the found opaque type
|
= note: expected type parameter `T2`
found closure `[closure@src/bin/my_lambda/main.rs:190:25: 195:6]`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `T2`
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(78条)