如何使用 hyper 在 Rust 中启动 Web 服务器?
How do I start a web server in Rust with hyper?
我想通过使用 hyper 框架编写反向代理来学习 Rust。我的 complete project is on GitHub. I'm stuck at starting a listener as 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() 中启动我的服务器。然后就可以了!
我想通过使用 hyper 框架编写反向代理来学习 Rust。我的 complete project is on GitHub. I'm stuck at starting a listener as 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() 中启动我的服务器。然后就可以了!