From 955e50313d828a066d38ba35e7cb511939af2f12 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 15 Oct 2017 14:53:03 -0700 Subject: [PATCH] simplify server method --- README.md | 5 +---- src/main.rs | 19 +++++++------------ src/server.rs | 37 ++++++++++++++++++++++++++++--------- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 6e2d92368..87d1d5875 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,6 @@ actix-web = { git = "https://github.com/fafhrd91/actix-web.git" } extern crate actix; extern crate actix_web; extern crate futures; -use std::net; -use std::str::FromStr; use actix::prelude::*; use actix_web::*; @@ -53,8 +51,7 @@ fn main() { }) ) .finish()) - .serve::<()>( - &net::SocketAddr::from_str("127.0.0.1:8880").unwrap()).unwrap(); + .serve::<_, ()>("127.0.0.1:8080").unwrap(); // stop system Arbiter::handle().spawn_fn(|| { diff --git a/src/main.rs b/src/main.rs index dcccb596b..bbf211b6b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,9 +5,6 @@ extern crate actix_web; extern crate tokio_core; extern crate env_logger; -use std::net; -use std::str::FromStr; - use actix::prelude::*; use actix_web::*; @@ -107,13 +104,12 @@ fn main() { HttpServer::new( RoutingMap::default() - .app( - "/blah", Application::default() - .resource("/test", |r| { - r.get::(); - r.post::(); - }) - .finish()) + .app("/blah", Application::default() + .resource("/test", |r| { + r.get::(); + r.post::(); + }) + .finish()) .resource("/test", |r| r.post::()) .resource("/ws/", |r| r.get::()) .resource("/simple/", |r| @@ -121,8 +117,7 @@ fn main() { httpcodes::HTTPOk })) .finish()) - .serve::<()>( - &net::SocketAddr::from_str("127.0.0.1:9080").unwrap()).unwrap(); + .serve::<_, ()>("127.0.0.1:9080").unwrap(); println!("starting"); let _ = sys.run(); diff --git a/src/server.rs b/src/server.rs index 76f1d1fb0..9b0508810 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,4 +1,4 @@ -use std::{io, net, mem}; +use std::{io, mem, net}; use std::rc::Rc; use std::time::Duration; use std::collections::VecDeque; @@ -28,15 +28,34 @@ impl HttpServer { } /// Start listening for incomming connections. - pub fn serve(self, addr: &net::SocketAddr) -> io::Result - where Self: ActorAddress + pub fn serve(self, addr: S) -> io::Result + where Self: ActorAddress, + S: net::ToSocketAddrs, { - let tcp = TcpListener::bind(addr, Arbiter::handle())?; - - Ok(HttpServer::create(move |ctx| { - ctx.add_stream(tcp.incoming()); - self - })) + let mut err = None; + let mut addrs = Vec::new(); + for iter in addr.to_socket_addrs() { + for addr in iter { + match TcpListener::bind(&addr, Arbiter::handle()) { + Ok(tcp) => addrs.push(tcp), + Err(e) => err = Some(e), + } + } + } + if addrs.is_empty() { + if let Some(e) = err.take() { + Err(e) + } else { + Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address.")) + } + } else { + Ok(HttpServer::create(move |ctx| { + for tcp in addrs { + ctx.add_stream(tcp.incoming()); + } + self + })) + } } }