我定义了一个路由和一个端点函数。我还注入了一些依赖项。
pub fn route1() -> BoxedFilter<(String, ParamType)> {
warp::get()
.and(warp::path::param())
.and(warp::filters::query::query())
.and(warp::path::end())
.boxed()
}
pub async fn handler1(
query: String,
param: ParamType,
dependency: DependencyType,
) -> Result<impl warp::Reply, warp::Rejection> {
}
Run Code Online (Sandbox Code Playgroud)
let api = api::routes::route1()
.and(warp::any().map(move || dependency))
.and_then(api::hanlders::hander1);
Run Code Online (Sandbox Code Playgroud)
这一切似乎工作正常。
但是,我希望能够在多个端点前面放置一些东西,以检查查询参数中的有效键。在里面handler1我可以添加:
if !param.key_valid {
return Ok(warp::reply::with_status(
warp::reply::json(&""),
StatusCode::BAD_REQUEST,
));
}
Run Code Online (Sandbox Code Playgroud)
我不想将它单独添加到每个处理程序中。
似乎我应该能够通过 来做到这一点filter,但我无法弄清楚。我试过使用.map()但随后返回多个项目将其转换为一个元组,我必须更改我的下游函数签名。理想情况下,我想找到一种方法来添加验证或其他过滤器,这些过滤器可以在没有任何下游值了解它们的情况下拒绝请求。
warp 的拒绝示例有效地证明了这一点:
拒绝表示过滤器不应继续处理请求,但不同的过滤器可以处理它的情况。
从“div-by”标题中提取分母,或使用 DivideByZero 拒绝。
你需要
Filter::and_then采取现有的过滤器(在这种情况下query()),并进行验证。如果验证失败,则返回自定义拒绝。Filter::recover适当地处理自定义拒绝和任何其他可能的错误。适用于您的情况:
use serde::Deserialize;
use std::{convert::Infallible, net::IpAddr};
use warp::{filters::BoxedFilter, http::StatusCode, reject::Reject, Filter, Rejection, Reply};
fn route1() -> BoxedFilter<(String, ParamType)> {
warp::get()
.and(warp::path::param())
.and(validated_query())
.and(warp::path::end())
.boxed()
}
#[derive(Debug)]
struct Invalid;
impl Reject for Invalid {}
fn validated_query() -> impl Filter<Extract = (ParamType,), Error = Rejection> + Copy {
warp::filters::query::query().and_then(|param: ParamType| async move {
if param.valid {
Ok(param)
} else {
Err(warp::reject::custom(Invalid))
}
})
}
async fn report_invalid(r: Rejection) -> Result<impl Reply, Infallible> {
let reply = warp::reply::reply();
if let Some(Invalid) = r.find() {
Ok(warp::reply::with_status(reply, StatusCode::BAD_REQUEST))
} else {
// Do better error handling here
Ok(warp::reply::with_status(
reply,
StatusCode::INTERNAL_SERVER_ERROR,
))
}
}
async fn handler1(
_query: String,
_param: ParamType,
_dependency: DependencyType,
) -> Result<impl warp::Reply, warp::Rejection> {
Ok(warp::reply::reply())
}
struct DependencyType;
#[derive(Deserialize)]
struct ParamType {
valid: bool,
}
#[tokio::main]
async fn main() {
let api = route1()
.and(warp::any().map(move || DependencyType))
.and_then(handler1)
.recover(report_invalid);
let ip: IpAddr = "127.0.0.1".parse().unwrap();
let port = 8888;
warp::serve(api).run((ip, port)).await;
}
Run Code Online (Sandbox Code Playgroud)
并且删除了不相关行的 curl 输出:
use serde::Deserialize;
use std::{convert::Infallible, net::IpAddr};
use warp::{filters::BoxedFilter, http::StatusCode, reject::Reject, Filter, Rejection, Reply};
fn route1() -> BoxedFilter<(String, ParamType)> {
warp::get()
.and(warp::path::param())
.and(validated_query())
.and(warp::path::end())
.boxed()
}
#[derive(Debug)]
struct Invalid;
impl Reject for Invalid {}
fn validated_query() -> impl Filter<Extract = (ParamType,), Error = Rejection> + Copy {
warp::filters::query::query().and_then(|param: ParamType| async move {
if param.valid {
Ok(param)
} else {
Err(warp::reject::custom(Invalid))
}
})
}
async fn report_invalid(r: Rejection) -> Result<impl Reply, Infallible> {
let reply = warp::reply::reply();
if let Some(Invalid) = r.find() {
Ok(warp::reply::with_status(reply, StatusCode::BAD_REQUEST))
} else {
// Do better error handling here
Ok(warp::reply::with_status(
reply,
StatusCode::INTERNAL_SERVER_ERROR,
))
}
}
async fn handler1(
_query: String,
_param: ParamType,
_dependency: DependencyType,
) -> Result<impl warp::Reply, warp::Rejection> {
Ok(warp::reply::reply())
}
struct DependencyType;
#[derive(Deserialize)]
struct ParamType {
valid: bool,
}
#[tokio::main]
async fn main() {
let api = route1()
.and(warp::any().map(move || DependencyType))
.and_then(handler1)
.recover(report_invalid);
let ip: IpAddr = "127.0.0.1".parse().unwrap();
let port = 8888;
warp::serve(api).run((ip, port)).await;
}
Run Code Online (Sandbox Code Playgroud)
Cargo.toml
[dependencies]
warp = "0.2.2"
serde = { version = "1.0.104", features = ["derive"] }
tokio = { version = "0.2.13", features = ["full"] }
Run Code Online (Sandbox Code Playgroud)