首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Hyper 0.12.x :为结构实现服务

Hyper 0.12.x :为结构实现服务
EN

Stack Overflow用户
提问于 2019-08-06 15:39:20
回答 1查看 490关注 0票数 3

在HYPER0.12.33中,如何为结构实现hyper::service::Service

我尝试了以下方法,但这还不够,因为在0.12中,似乎不再自动为实现Service的结构提供Future特征

代码语言:javascript
复制
use futures::future::Future;
use hyper::{Body, Request, Response};

struct MyStruct;

impl MyStruct {
    pub fn new() -> Self {
        MyStruct
    }
}

impl hyper::service::Service for MyStruct {
    type ReqBody = Body;
    type ResBody = Body;
    type Error = hyper::Error;
    type Future = Box<Future<Item = Response<Body>, Error = hyper::Error>>;

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        unimplemented!()
    }
}

fn main() {
    let addr = "0.0.0.0:8080".parse().unwrap();
    let server = hyper::Server::bind(&addr)
        .serve(|| MyStruct::new())
        .map_err(|e| eprintln!("server error: {}", e));

    hyper::rt::run(server);
}

给出了构建错误消息:

代码语言:javascript
复制
Standard Error

   Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `MyStruct: futures::future::Future` is not satisfied
  --> src/main.rs:26:10
   |
26 |         .serve(|| MyStruct::new())
   |          ^^^^^ the trait `futures::future::Future` is not implemented for `MyStruct`
   |
   = note: required because of the requirements on the impl of `hyper::service::make_service::MakeServiceRef<hyper::server::tcp::addr_stream::AddrStream>` for `[closure@src/main.rs:26:16: 26:34]`

error[E0599]: no method named `map_err` found for type `hyper::server::Server<hyper::server::tcp::AddrIncoming, [closure@src/main.rs:26:16: 26:34]>` in the current scope
  --> src/main.rs:27:10
   |
27 |         .map_err(|e| eprintln!("server error: {}", e));
   |          ^^^^^^^
   |
   = note: the method `map_err` exists but the following trait bounds were not satisfied:
           `&mut hyper::server::Server<hyper::server::tcp::AddrIncoming, [closure@src/main.rs:26:16: 26:34]> : futures::future::Future`
           `hyper::server::Server<hyper::server::tcp::AddrIncoming, [closure@src/main.rs:26:16: 26:34]> : futures::future::Future`
EN

回答 1

Stack Overflow用户

发布于 2021-09-15 16:33:45

This example给出了一种方法。它使用v0.14.12编译和运行

代码语言:javascript
复制
#![deny(warnings)]

use std::task::{Context, Poll};

use futures_util::future;
use hyper::service::Service;
use hyper::{Body, Request, Response, Server};

const ROOT: &str = "/";

#[derive(Debug)]
pub struct Svc;

impl Service<Request<Body>> for Svc {
    type Response = Response<Body>;
    type Error = hyper::Error;
    type Future = future::Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Ok(()).into()
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let rsp = Response::builder();

        let uri = req.uri();
        if uri.path() != ROOT {
            let body = Body::from(Vec::new());
            let rsp = rsp.status(404).body(body).unwrap();
            return future::ok(rsp);
        }

        let body = Body::from(Vec::from(&b"heyo!"[..]));
        let rsp = rsp.status(200).body(body).unwrap();
        future::ok(rsp)
    }
}

pub struct MakeSvc;

impl<T> Service<T> for MakeSvc {
    type Response = Svc;
    type Error = std::io::Error;
    type Future = future::Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Ok(()).into()
    }

    fn call(&mut self, _: T) -> Self::Future {
        future::ok(Svc)
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // pretty_env_logger::init();

    let addr = "127.0.0.1:1337".parse().unwrap();

    let server = Server::bind(&addr).serve(MakeSvc);

    println!("Listening on http://{}", addr);

    server.await?;

    Ok(())
}

间接性(MakeSvc ->源)似乎遵循this issue中所述的Hyper体系结构

这里涉及两个步骤,这两个步骤都使用服务:

  1. MakeSvc是为每个MakeSvc创建服务的服务,是处理单个连接上的请求的服务。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57371130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档