This repository has been archived by the owner on Mar 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http-server.rs
65 lines (53 loc) · 1.81 KB
/
http-server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use futures::{future, Future, Poll, Stream};
use hyper::{self, Body, Request, Response};
use tokio::net::TcpListener;
use tower::{builder::ServiceBuilder, Service};
use tower_hyper::server::Server;
fn main() {
hyper::rt::run(future::lazy(|| {
let addr = "127.0.0.1:3000".parse().unwrap();
let bind = TcpListener::bind(&addr).expect("bind");
println!("Listening on http://{}", addr);
let maker = ServiceBuilder::new().concurrency_limit(5).service(MakeSvc);
let server = Server::new(maker);
bind.incoming()
.fold(server, |mut server, stream| {
if let Err(e) = stream.set_nodelay(true) {
return Err(e);
}
hyper::rt::spawn(
server
.serve(stream)
.map_err(|e| panic!("Server error {:?}", e)),
);
Ok(server)
})
.map_err(|e| panic!("serve error: {:?}", e))
.map(|_| {})
}));
}
struct Svc;
impl Service<Request<Body>> for Svc {
type Response = Response<Body>;
type Error = hyper::Error;
type Future = future::FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(().into())
}
fn call(&mut self, _req: Request<Body>) -> Self::Future {
let res = Response::new(Body::from("Hello World!"));
future::ok(res)
}
}
struct MakeSvc;
impl Service<()> for MakeSvc {
type Response = Svc;
type Error = hyper::Error;
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error> + Send + 'static>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(().into())
}
fn call(&mut self, _: ()) -> Self::Future {
Box::new(future::ok(Svc))
}
}