mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-24 07:53:00 +01:00
http server accepts factory of HttpHandlers
This commit is contained in:
parent
b9da09ddf0
commit
e9aa67b75d
@ -57,7 +57,7 @@ fn main() {
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::new()
|
||||
|| Application::new()
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// cookie session middleware
|
||||
|
@ -54,13 +54,14 @@ impl Handler<ws::Message> for MyWebSocket {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
let _ = env_logger::init();
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::with_state(AppState{counter: Cell::new(0)})
|
||||
|| Application::with_state(AppState{counter: Cell::new(0)})
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// websocket route
|
||||
|
@ -61,7 +61,7 @@ fn main() {
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::new()
|
||||
|| Application::new()
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// websocket route
|
||||
|
@ -55,10 +55,10 @@ request handler with the application's `resource` on a particular *HTTP method*
|
||||
```
|
||||
|
||||
After that, application instance can be used with `HttpServer` to listen for incoming
|
||||
connections:
|
||||
connections. Server accepts function that should return `HttpHandler` instance:
|
||||
|
||||
```rust,ignore
|
||||
HttpServer::new(app).serve::<_, ()>("127.0.0.1:8088");
|
||||
HttpServer::new(|| app).serve::<_, ()>("127.0.0.1:8088");
|
||||
```
|
||||
|
||||
That's it. Now, compile and run the program with cargo run.
|
||||
@ -79,7 +79,7 @@ fn main() {
|
||||
let sys = actix::System::new("example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::new()
|
||||
|| Application::new()
|
||||
.resource("/", |r| r.f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
|
||||
|
@ -42,7 +42,7 @@ Multiple applications could be served with one server:
|
||||
use actix_web::*;
|
||||
|
||||
fn main() {
|
||||
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
||||
HttpServer::<TcpStream, SocketAddr, _>::new(|| vec![
|
||||
Application::new()
|
||||
.prefix("/app1")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||
|
@ -81,7 +81,7 @@ fn main() {
|
||||
let sys = actix::System::new("example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::new()
|
||||
|| Application::new()
|
||||
.resource("/", |r| r.method(Method::GET).f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
|
||||
|
@ -19,7 +19,7 @@ pub struct HttpApplication<S> {
|
||||
middlewares: Rc<Vec<Box<Middleware<S>>>>,
|
||||
}
|
||||
|
||||
impl<S: 'static> HttpApplication<S> {
|
||||
impl<S: Send + 'static> HttpApplication<S> {
|
||||
|
||||
pub(crate) fn prepare_request(&self, req: HttpRequest) -> HttpRequest<S> {
|
||||
req.with_state(Rc::clone(&self.state), self.router.clone())
|
||||
@ -34,7 +34,7 @@ impl<S: 'static> HttpApplication<S> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: 'static> HttpHandler for HttpApplication<S> {
|
||||
impl<S: Send + 'static> HttpHandler for HttpApplication<S> {
|
||||
|
||||
fn handle(&self, req: HttpRequest) -> Result<Box<HttpHandlerTask>, HttpRequest> {
|
||||
if req.path().starts_with(&self.prefix) {
|
||||
@ -89,7 +89,7 @@ impl Default for Application<()> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Application<S> where S: 'static {
|
||||
impl<S> Application<S> where S: Send + 'static {
|
||||
|
||||
/// Create application with specific state. Application can be
|
||||
/// configured with builder-like pattern.
|
||||
@ -133,7 +133,7 @@ impl<S> Application<S> where S: 'static {
|
||||
/// .finish();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn prefix<P: Into<String>>(&mut self, prefix: P) -> &mut Self {
|
||||
pub fn prefix<P: Into<String>>(mut self, prefix: P) -> Application<S> {
|
||||
{
|
||||
let parts = self.parts.as_mut().expect("Use after finish");
|
||||
let mut prefix = prefix.into();
|
||||
@ -176,7 +176,7 @@ impl<S> Application<S> where S: 'static {
|
||||
/// .finish();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn resource<F>(&mut self, path: &str, f: F) -> &mut Self
|
||||
pub fn resource<F>(mut self, path: &str, f: F) -> Application<S>
|
||||
where F: FnOnce(&mut Resource<S>) + 'static
|
||||
{
|
||||
{
|
||||
@ -197,7 +197,7 @@ impl<S> Application<S> where S: 'static {
|
||||
}
|
||||
|
||||
/// Default resource is used if no matched route could be found.
|
||||
pub fn default_resource<F>(&mut self, f: F) -> &mut Self
|
||||
pub fn default_resource<F>(mut self, f: F) -> Application<S>
|
||||
where F: FnOnce(&mut Resource<S>) + 'static
|
||||
{
|
||||
{
|
||||
@ -230,7 +230,7 @@ impl<S> Application<S> where S: 'static {
|
||||
/// .finish();
|
||||
/// }
|
||||
/// ```
|
||||
pub fn external_resource<T, U>(&mut self, name: T, url: U) -> &mut Self
|
||||
pub fn external_resource<T, U>(mut self, name: T, url: U) -> Application<S>
|
||||
where T: AsRef<str>, U: AsRef<str>
|
||||
{
|
||||
{
|
||||
@ -246,7 +246,7 @@ impl<S> Application<S> where S: 'static {
|
||||
}
|
||||
|
||||
/// Register a middleware
|
||||
pub fn middleware<T>(&mut self, mw: T) -> &mut Self
|
||||
pub fn middleware<T>(mut self, mw: T) -> Application<S>
|
||||
where T: Middleware<S> + 'static
|
||||
{
|
||||
self.parts.as_mut().expect("Use after finish")
|
||||
@ -274,7 +274,7 @@ impl<S> Application<S> where S: 'static {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: 'static> IntoHttpHandler for Application<S> {
|
||||
impl<S: Send + 'static> IntoHttpHandler for Application<S> {
|
||||
type Handler = HttpApplication<S>;
|
||||
|
||||
fn into_handler(mut self) -> HttpApplication<S> {
|
||||
@ -282,7 +282,7 @@ impl<S: 'static> IntoHttpHandler for Application<S> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
|
||||
impl<'a, S: Send + 'static> IntoHttpHandler for &'a mut Application<S> {
|
||||
type Handler = HttpApplication<S>;
|
||||
|
||||
fn into_handler(self) -> HttpApplication<S> {
|
||||
@ -291,7 +291,7 @@ impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
impl<S: 'static> Iterator for Application<S> {
|
||||
impl<S: Send + 'static> Iterator for Application<S> {
|
||||
type Item = HttpApplication<S>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
|
@ -95,10 +95,11 @@ impl<T: 'static, A: 'static, H: 'static> Actor for HttpServer<T, A, H> {
|
||||
impl<T, A, H> HttpServer<T, A, H> where H: HttpHandler
|
||||
{
|
||||
/// Create new http server with vec of http handlers
|
||||
pub fn new<V, U: IntoIterator<Item=V>>(handler: U) -> Self
|
||||
where V: IntoHttpHandler<Handler=H>
|
||||
pub fn new<V, F, U: IntoIterator<Item=V>>(factory: F) -> Self
|
||||
where F: Fn() -> U + Send,
|
||||
V: IntoHttpHandler<Handler=H>
|
||||
{
|
||||
let apps: Vec<_> = handler.into_iter().map(|h| h.into_handler()).collect();
|
||||
let apps: Vec<_> = factory().into_iter().map(|h| h.into_handler()).collect();
|
||||
|
||||
HttpServer{ h: Rc::new(apps),
|
||||
io: PhantomData,
|
||||
|
@ -4,6 +4,7 @@ extern crate tokio_core;
|
||||
extern crate reqwest;
|
||||
|
||||
use std::{net, thread};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio_core::net::TcpListener;
|
||||
@ -16,7 +17,7 @@ fn test_serve() {
|
||||
thread::spawn(|| {
|
||||
let sys = System::new("test");
|
||||
let srv = HttpServer::new(
|
||||
vec![Application::new()
|
||||
|| vec![Application::new()
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))]);
|
||||
srv.serve::<_, ()>("127.0.0.1:58902").unwrap();
|
||||
sys.run();
|
||||
@ -36,7 +37,7 @@ fn test_serve_incoming() {
|
||||
let sys = System::new("test");
|
||||
|
||||
let srv = HttpServer::new(
|
||||
Application::new()
|
||||
|| Application::new()
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk)));
|
||||
let tcp = TcpListener::from_listener(tcp, &addr2, Arbiter::handle()).unwrap();
|
||||
srv.serve_incoming::<_, ()>(tcp.incoming(), false).unwrap();
|
||||
@ -51,6 +52,7 @@ struct MiddlewareTest {
|
||||
start: Arc<AtomicUsize>,
|
||||
response: Arc<AtomicUsize>,
|
||||
finish: Arc<AtomicUsize>,
|
||||
test: Rc<usize>,
|
||||
}
|
||||
|
||||
impl<S> middlewares::Middleware<S> for MiddlewareTest {
|
||||
@ -84,12 +86,11 @@ fn test_middlewares() {
|
||||
let sys = System::new("test");
|
||||
|
||||
HttpServer::new(
|
||||
vec![Application::new()
|
||||
.middleware(MiddlewareTest{start: act_num1,
|
||||
response: act_num2,
|
||||
finish: act_num3})
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))
|
||||
.finish()])
|
||||
move || vec![Application::new()
|
||||
.middleware(MiddlewareTest{start: act_num1.clone(),
|
||||
response: act_num2.clone(),
|
||||
finish: act_num3.clone(), test: Rc::new(1)})
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))])
|
||||
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
||||
sys.run();
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user