1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-25 09:59:21 +02:00

simplify application creation

This commit is contained in:
Nikolay Kim
2017-12-06 11:00:39 -08:00
parent 87c7441f7d
commit c63f058647
26 changed files with 150 additions and 138 deletions

View File

@ -3,11 +3,10 @@ use std::collections::HashMap;
use error::UriGenerationError;
use handler::{Reply, RouteHandler};
use route::Route;
use resource::Resource;
use recognizer::{RouteRecognizer, check_pattern, PatternElement};
use httprequest::HttpRequest;
use channel::HttpHandler;
use channel::{HttpHandler, IntoHttpHandler};
use pipeline::Pipeline;
use middlewares::Middleware;
@ -56,16 +55,15 @@ impl<S: 'static> Router<S> {
}
/// Application
pub struct Application<S> {
pub struct HttpApplication<S> {
state: Rc<S>,
prefix: String,
default: Resource<S>,
routes: Vec<(String, Route<S>)>,
router: Router<S>,
middlewares: Rc<Vec<Box<Middleware>>>,
}
impl<S: 'static> Application<S> {
impl<S: 'static> HttpApplication<S> {
fn run(&self, req: HttpRequest) -> Reply {
let mut req = req.with_state(Rc::clone(&self.state));
@ -73,21 +71,16 @@ impl<S: 'static> Application<S> {
if let Some((params, h)) = self.router.0.recognize(req.path()) {
if let Some(params) = params {
req.set_match_info(params);
req.set_prefix(self.router.0.prefix());
}
h.handle(req)
} else {
for route in &self.routes {
if req.path().starts_with(&route.0) && route.1.check(&mut req) {
req.set_prefix(route.0.len());
return route.1.handle(req)
}
}
self.default.handle(req)
}
}
}
impl<S: 'static> HttpHandler for Application<S> {
impl<S: 'static> HttpHandler for HttpApplication<S> {
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest> {
if req.path().starts_with(&self.prefix) {
@ -99,16 +92,31 @@ impl<S: 'static> HttpHandler for Application<S> {
}
}
struct ApplicationParts<S> {
state: S,
prefix: String,
default: Resource<S>,
resources: HashMap<String, Resource<S>>,
middlewares: Vec<Box<Middleware>>,
}
/// Structure that follows the builder pattern for building `Application` structs.
pub struct Application<S=()> {
parts: Option<ApplicationParts<S>>,
}
impl Application<()> {
/// Create default `ApplicationBuilder` with no state
pub fn default<T: Into<String>>(prefix: T) -> ApplicationBuilder<()> {
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
/// Create application with empty state. Application can
/// be configured with builder-like pattern.
///
/// This method accepts path prefix for which it should serve requests.
pub fn new<T: Into<String>>(prefix: T) -> Application<()> {
Application {
parts: Some(ApplicationParts {
state: (),
prefix: prefix.into(),
default: Resource::default_not_found(),
routes: Vec::new(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
@ -118,38 +126,22 @@ impl Application<()> {
impl<S> Application<S> where S: 'static {
/// Create application builder with specific state. State is shared with all
/// routes within same application and could be
/// accessed with `HttpContext::state()` method.
pub fn build<T: Into<String>>(prefix: T, state: S) -> ApplicationBuilder<S> {
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
/// Create application with specific state. Application can be
/// configured with builder-like pattern.
///
/// State is shared with all reousrces within same application and could be
/// accessed with `HttpRequest::state()` method.
pub fn with_state<T: Into<String>>(prefix: T, state: S) -> Application<S> {
Application {
parts: Some(ApplicationParts {
state: state,
prefix: prefix.into(),
default: Resource::default_not_found(),
routes: Vec::new(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
}
}
}
struct ApplicationBuilderParts<S> {
state: S,
prefix: String,
default: Resource<S>,
routes: Vec<(String, Route<S>)>,
resources: HashMap<String, Resource<S>>,
middlewares: Vec<Box<Middleware>>,
}
/// Structure that follows the builder pattern for building `Application` structs.
pub struct ApplicationBuilder<S=()> {
parts: Option<ApplicationBuilderParts<S>>,
}
impl<S> ApplicationBuilder<S> where S: 'static {
/// Configure resource for specific path.
///
@ -170,11 +162,11 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// store userid and friend in the exposed Params object:
///
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default("/")
/// let app = Application::new("/")
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
@ -219,39 +211,43 @@ impl<S> ApplicationBuilder<S> where S: 'static {
self
}
/// Construct application
pub fn finish(&mut self) -> Application<S> {
/// Finish application configuration and create HttpHandler object
pub fn finish(&mut self) -> HttpApplication<S> {
let parts = self.parts.take().expect("Use after finish");
let prefix = if parts.prefix.ends_with('/') {
parts.prefix
} else {
parts.prefix + "/"
};
let mut routes = Vec::new();
for (path, route) in parts.routes {
routes.push((prefix.clone() + path.trim_left_matches('/'), route));
}
Application {
HttpApplication {
state: Rc::new(parts.state),
prefix: prefix.clone(),
default: parts.default,
routes: routes,
router: Router::new(prefix, parts.resources),
middlewares: Rc::new(parts.middlewares),
}
}
}
impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
builder.finish()
impl<S: 'static> IntoHttpHandler for Application<S> {
type Handler = HttpApplication<S>;
fn into_handler(mut self) -> HttpApplication<S> {
self.finish()
}
}
impl<S: 'static> Iterator for ApplicationBuilder<S> {
type Item = Application<S>;
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
type Handler = HttpApplication<S>;
fn into_handler(self) -> HttpApplication<S> {
self.finish()
}
}
#[doc(hidden)]
impl<S: 'static> Iterator for Application<S> {
type Item = HttpApplication<S>;
fn next(&mut self) -> Option<Self::Item> {
if self.parts.is_some() {

View File

@ -17,6 +17,23 @@ pub trait HttpHandler: 'static {
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest>;
}
/// Conversion helper trait
pub trait IntoHttpHandler {
/// The associated type which is result of conversion.
type Handler: HttpHandler;
/// Convert into `HttpHandler` object.
fn into_handler(self) -> Self::Handler;
}
impl<T: HttpHandler> IntoHttpHandler for T {
type Handler = T;
fn into_handler(self) -> Self::Handler {
self
}
}
enum HttpProtocol<T, H>
where T: AsyncRead + AsyncWrite + 'static, H: 'static
{

View File

@ -12,9 +12,8 @@
pub use info::ConnectionInfo;
pub use handler::Handler;
pub use pipeline::Pipeline;
pub use channel::{HttpChannel, HttpHandler};
pub use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
pub use recognizer::{FromParam, RouteRecognizer, Pattern, PatternElement};
pub use cookie::CookieBuilder;
pub use application::ApplicationBuilder;
pub use httpresponse::HttpResponseBuilder;

View File

@ -227,7 +227,7 @@ pub enum HttpRangeError {
InvalidRange,
/// Returned if first-byte-pos of all of the byte-range-spec
/// values is greater than the content size.
/// See https://github.com/golang/go/commit/aa9b3d7
/// See `https://github.com/golang/go/commit/aa9b3d7`
#[fail(display="First-byte-pos of all of the byte-range-spec values is greater than the content size")]
NoOverlap,
}

View File

@ -194,11 +194,12 @@ impl FromRequest for FilesystemElement {
/// Can be registered with `Application::route_handler()`.
///
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::{fs, Application};
///
/// fn main() {
/// let app = actix_web::Application::default("/")
/// .resource("/static", |r| r.h(actix_web::fs::StaticFiles::new(".", true)))
/// let app = Application::new("/")
/// .resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
/// .finish();
/// }
/// ```

View File

@ -1,4 +1,4 @@
//! Web framework for [Actix](https://github.com/actix/actix)
//! Actix web is a small, fast, down-to-earth, open source rust web framework.
#![cfg_attr(actix_nightly, feature(
specialization, // for impl ErrorResponse for std::error::Error

View File

@ -11,11 +11,11 @@ use middlewares::{Response, Middleware};
/// This middleware does not set header if response headers already contains it.
///
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default("/")
/// let app = Application::new("/")
/// .middleware(
/// middlewares::DefaultHeaders::build()
/// .header("X-Version", "0.2")

View File

@ -22,12 +22,12 @@ use middlewares::{Middleware, Started, Finished};
/// %a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
/// ```
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::Application;
/// use actix_web::middlewares::Logger;
///
/// fn main() {
/// let app = Application::default("/")
/// let app = Application::new("/")
/// .middleware(Logger::default())
/// .middleware(Logger::new("%a %{User-Agent}i"))
/// .finish();

View File

@ -241,6 +241,11 @@ impl<T> RouteRecognizer<T> {
self.patterns.get(name)
}
/// Length of the prefix
pub fn prefix(&self) -> usize {
self.prefix
}
pub fn set_prefix<P: Into<String>>(&mut self, prefix: P) {
let p = prefix.into();
if p.ends_with('/') {

View File

@ -18,13 +18,13 @@ use httprequest::HttpRequest;
/// route considired matched and route handler get called.
///
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default("/")
/// let app = Application::new("/")
/// .resource(
/// "/", |r| r.route().method(Method::GET).f(|r| HttpResponse::Ok()))
/// "/", |r| r.method(Method::GET).f(|r| HttpResponse::Ok()))
/// .finish();
/// }
pub struct Resource<S=()> {
@ -67,11 +67,11 @@ impl<S> Resource<S> where S: 'static {
/// *Route* is used for route configuration, i.e. adding predicates, setting up handler.
///
/// ```rust
/// extern crate actix_web;
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default("/")
/// let app = Application::new("/")
/// .resource(
/// "/", |r| r.route()
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
@ -87,7 +87,8 @@ impl<S> Resource<S> where S: 'static {
/// Register a new route and add method check to route.
///
/// This is sortcut for:
/// This is shortcut for:
///
/// ```rust,ignore
/// Resource::resource("/", |r| r.route().method(Method::GET).f(index)
/// ```
@ -98,7 +99,8 @@ impl<S> Resource<S> where S: 'static {
/// Register a new route and add handler object.
///
/// This is sortcut for:
/// This is shortcut for:
///
/// ```rust,ignore
/// Resource::resource("/", |r| r.route().h(handler)
/// ```
@ -109,7 +111,8 @@ impl<S> Resource<S> where S: 'static {
/// Register a new route and add handler function.
///
/// This is sortcut for:
/// This is shortcut for:
///
/// ```rust,ignore
/// Resource::resource("/", |r| r.route().f(index)
/// ```

View File

@ -24,7 +24,7 @@ use openssl::pkcs12::ParsedPkcs12;
#[cfg(feature="alpn")]
use tokio_openssl::{SslStream, SslAcceptorExt};
use channel::{HttpChannel, HttpHandler};
use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
/// An HTTP Server
@ -47,8 +47,10 @@ 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<U: IntoIterator<Item=H>>(handler: U) -> Self {
let apps: Vec<_> = handler.into_iter().collect();
pub fn new<V, U: IntoIterator<Item=V>>(handler: U) -> Self
where V: IntoHttpHandler<Handler=H>
{
let apps: Vec<_> = handler.into_iter().map(|h| h.into_handler()).collect();
HttpServer {h: Rc::new(apps),
io: PhantomData,

View File

@ -42,7 +42,7 @@
//! }
//!
//! fn main() {
//! Application::default("/")
//! Application::new("/")
//! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route
//! .finish();
//! }