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;
}
并删除了不相关行的 curl 输出:
% curl -v '127.0.0.1:8888/dummy/?valid=false'
< HTTP/1.1 400 Bad Request
% curl -v '127.0.0.1:8888/dummy/?valid=true'
< HTTP/1.1 200 OK
货运.toml
[dependencies]
warp = "0.2.2"
serde = { version = "1.0.104", features = ["derive"] }
tokio = { version = "0.2.13", features = ["full"] }