Rust 如何编写返回json或html的简单warp处理程序?

Rust 如何编写返回json或html的简单warp处理程序?,rust,rust-tokio,rust-warp,Rust,Rust Tokio,Rust Warp,我有以下资料: 使用warp::Filter; 发布结构路由器{} impl路由器{ pub异步fn句柄( &自我, )->std::result::result{ let uri=“/path”; 匹配uri{ “/指标列表”=>{ 设为空:Vec=Vec::new(); Ok(warp::reply::json(&empty)) } “/metrics ips”=>{ 设为空:Vec=Vec::new(); Ok(warp::reply::json(&empty)) } &_ => { 错误

我有以下资料:

使用warp::Filter;
发布结构路由器{}
impl路由器{
pub异步fn句柄(
&自我,
)->std::result::result{
let uri=“/path”;
匹配uri{
“/指标列表”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty))
}
“/metrics ips”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty))
}
&_ => {
错误(warp::reject::reject())
}
}
}
}
#[tokio::main]
发布异步fn main(){
设r=路由器{};
让handler=warp::path(“/”).map(| | r.handle());
翘曲:发球(手);
//.运行([0,0,0,0,0],3000))
//.等待;
}
但即使使用这个简化的示例,我也会得到一个错误:

error[E0277]: the trait bound `impl warp::Future: warp::Reply` is not satisfied
  --> src/main.rs:41:17
   |
41 |     warp::serve(handler);
   |                 ^^^^^^^ the trait `warp::Reply` is not implemented for `impl warp::Future`
   |
  ::: $HOME/.cargo/registry/src/github.com-1ecc6299db9ec823/warp-0.2.5/src/server.rs:26:17
   |
26 |     F::Extract: Reply,
   |                 ----- required by this bound in `warp::serve`
   |
   = note: required because of the requirements on the impl of `warp::Reply` for `(impl warp::Future,)`

为什么会这样?

一种解决方案是在所有回复上调用
.into_response()
,然后将返回类型从
std::result::result
更改为
std::result::result

pub异步fn句柄(
&自我,
)->std::result::result{
let uri=“/path”;
匹配uri{
“/指标列表”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty).into_response())
}
“/metrics ips”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty).into_response())
}
&_ => {
错误(将::拒绝::拒绝()
}
}
}

原因是如果我理解正确,在返回类型中有一个
impl Trait
可以让您一次只使用一个实现该特性的类型,因为您的函数只能有一个返回类型。

一个解决方案是调用
.into\u response()
在所有回复上,然后将返回类型从
std::result::result
更改为
std::result::result

pub异步fn句柄(
&自我,
)->std::result::result{
let uri=“/path”;
匹配uri{
“/指标列表”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty).into_response())
}
“/metrics ips”=>{
设为空:Vec=Vec::new();
Ok(warp::reply::json(&empty).into_response())
}
&_ => {
错误(将::拒绝::拒绝()
}
}
}
原因是如果我理解正确的话,在返回类型中有一个
impl Trait
可以让您一次只使用一个实现该特性的类型,因为您的函数只能有一个返回类型

pub async fn handle(
        &self,
    ) -> std::result::Result<warp::reply::Response, warp::Rejection> {

        let uri = "/path";

        match uri {
            "/metrics-list" => {
                let empty : Vec<u8> = Vec::new();
                Ok(warp::reply::json(&empty).into_response())
            }

            "/metrics-ips" => {
                let empty : Vec<u8> = Vec::new();
                Ok(warp::reply::json(&empty).into_response())
            }

            &_ => {
                Err(warp::reject::reject().into_response())
            }
        }
    }