rust - 如何使用 hyper 在 Rust 中启动 Web 服务器?

标签 rust hyper

我想通过使用 super 框架编写反向代理来学习 Rust。我的complete project is on GitHub .我坚持以 explained in the documentation 的身份启动监听器:

extern crate hyper;

use hyper::Client;
use hyper::server::{Server, Request, Response};
use std::io::Read;

fn pipe_through(req: Request, res: Response) {
    let client = Client::new();
    // Why does the response have to be mutable here? We never need to modify it, so we should be
    // able to remove "mut"?
    let mut response = client.get("http://drupal-8.localhost/").send().unwrap();
    // Print out all the headers first.
    for header in response.headers.iter() {
        println!("{}", header);
    }
    // Now the body. This is ugly, why do I have to create an intermediary string variable? I want
    // to push the response directly to stdout.
    let mut body = String::new();
    response.read_to_string(&mut body).unwrap();
    print!("{}", body);
}

Server::http("127.0.0.1:9090").unwrap().handle(pipe_through).unwrap();

这不起作用,并因以下编译错误而失败:

error: expected one of `!` or `::`, found `(`
  --> src/main.rs:23:13
   |
23 | Server::http("127.0.0.1:9090").unwrap().handle(pipe_through).unwrap();
   |             ^

为什么我对 http() 的调用不正确?它不应该按照文档中的指示创建一个新服务器吗?

最佳答案

Rust 中的所有表达式都必须在函数内,因此我需要在 fn main() 中启动我的服务器。然后就可以了!

关于rust - 如何使用 hyper 在 Rust 中启动 Web 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086033/

相关文章:

proxy - 有条件地使用ProxyConnector或HTTPConnector

error-handling - 如何处理 rust 上的盒装和链式错误?

Rust Cargo init 发生签名验证失败

rust - 在 Hyper 0.11 中找不到类型 `post` 的名为 `hyper::Client` 的方法

rust - 如何在 Rust 中使用自由类型绑定(bind)?

rust - 关于 Rust 中的借用的困惑

rust - 为 Rust 的 hyper http crate 使用自定义传输器

rust - 使用 hyper 将 block 流异步写入文件

rust - 如何在循环中从可变字符串中删除字符?

rust - 我需要帮助在不同的函数中使用可变引用