mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-23 23:51:06 +01:00
simplify application creation
This commit is contained in:
parent
87c7441f7d
commit
c63f058647
@ -3,7 +3,6 @@
|
||||
Actix web is a small, fast, down-to-earth, open source rust web framework.
|
||||
|
||||
```rust,ignore
|
||||
extern crate actix_web;
|
||||
use actix_web::*;
|
||||
|
||||
fn index(req: HttpRequest) -> String {
|
||||
@ -12,7 +11,7 @@ fn index(req: HttpRequest) -> String {
|
||||
|
||||
fn main() {
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/{name}", |r| r.method(Method::GET).f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8080");
|
||||
}
|
||||
|
@ -57,7 +57,7 @@ fn main() {
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// cookie session middleware
|
||||
|
@ -60,13 +60,13 @@ fn main() {
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::build("/", AppState{counter: Cell::new(0)})
|
||||
Application::with_state("/", AppState{counter: Cell::new(0)})
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// websocket route
|
||||
.resource(
|
||||
"/ws/", |r| r.method(Method::GET)
|
||||
.f(|req| ws::start(req, MyWebSocket{counter: 0})))
|
||||
"/ws/", |r|
|
||||
r.method(Method::GET).f(|req| ws::start(req, MyWebSocket{counter: 0})))
|
||||
// register simple handler, handle all methods
|
||||
.resource("/", |r| r.f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||
|
@ -61,7 +61,7 @@ fn main() {
|
||||
let sys = actix::System::new("ws-example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
// enable logger
|
||||
.middleware(middlewares::Logger::default())
|
||||
// websocket route
|
||||
|
@ -15,12 +15,12 @@ Default `Logger` could be created with `default` method, it uses the default for
|
||||
%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() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.middleware(Logger::default())
|
||||
.middleware(Logger::new("%a %{User-Agent}i"))
|
||||
.finish();
|
||||
@ -67,11 +67,11 @@ Tto set default response headers `DefaultHeaders` middleware could be used.
|
||||
*DefaultHeaders* 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")
|
||||
|
@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -32,7 +32,7 @@ To serve files from specific directory and sub-directories `StaticFiles` could b
|
||||
use actix_web::*;
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/static", |r| r.h(fs::StaticFiles::new(".", true)))
|
||||
.finish();
|
||||
}
|
||||
|
@ -26,8 +26,8 @@ fn main() {
|
||||
let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap().parse("12345").unwrap();
|
||||
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
.route("/index.html", |r| r.f(index))
|
||||
Application::new("/")
|
||||
.resource("/index.html", |r| r.f(index))
|
||||
.serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
|
||||
}
|
||||
```
|
||||
|
@ -48,7 +48,7 @@ request handler with the application's `resource` on a particular *HTTP method*
|
||||
# "Hello world!"
|
||||
# }
|
||||
# fn main() {
|
||||
let app = Application::default("/")
|
||||
let app = Application::new("/")
|
||||
.resource("/", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
# }
|
||||
@ -79,7 +79,7 @@ fn main() {
|
||||
let sys = actix::System::new("example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/", |r| r.f(index)))
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
|
||||
|
@ -20,7 +20,7 @@ has same url path prefix:
|
||||
# "Hello world!"
|
||||
# }
|
||||
# fn main() {
|
||||
let app = Application::default("/prefix")
|
||||
let app = Application::new("/prefix")
|
||||
.resource("/index.html", |r| r.method(Method::GET).f(index))
|
||||
.finish()
|
||||
# }
|
||||
@ -40,15 +40,12 @@ use tokio_core::net::TcpStream;
|
||||
|
||||
fn main() {
|
||||
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
||||
Application::default("/app1")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
||||
.finish(),
|
||||
Application::default("/app2")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
||||
.finish(),
|
||||
Application::default("/")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk))
|
||||
.finish(),
|
||||
Application::new("/app1")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||
Application::new("/app2")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||
Application::new("/")
|
||||
.resource("/", |r| r.f(|r| httpcodes::HTTPOk)),
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
@ -46,8 +46,8 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
Let's create response for custom type that serializes to `application/json` response:
|
||||
|
||||
```rust
|
||||
extern crate actix;
|
||||
extern crate actix_web;
|
||||
# extern crate actix;
|
||||
# extern crate actix_web;
|
||||
extern crate serde;
|
||||
extern crate serde_json;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
@ -77,7 +77,7 @@ fn main() {
|
||||
let sys = actix::System::new("example");
|
||||
|
||||
HttpServer::new(
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/", |r| r.method(
|
||||
Method::GET).f(|req| {MyObj{name: "user".to_owned()}})))
|
||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||
@ -113,7 +113,7 @@ fn index(req: HttpRequest) -> FutureResult<HttpResponse, Error> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/async", |r| r.route().a(index))
|
||||
.finish();
|
||||
}
|
||||
@ -138,7 +138,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/async", |r| r.f(index))
|
||||
.finish();
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/prefix", |r| r.f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -36,7 +36,7 @@ fn index(req: HttpRequest) -> HttpResponse {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/app")
|
||||
Application::new("/app")
|
||||
.resource("/prefix", |r| r.f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -53,7 +53,7 @@ if no route could be matched default response `HTTPMethodNotAllowed` get resturn
|
||||
# use actix_web::*;
|
||||
#
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/prefix", |r| {
|
||||
r.method(Method::GET).h(httpcodes::HTTPOk);
|
||||
r.method(Method::POST).h(httpcodes::HTTPForbidden);
|
||||
@ -86,7 +86,7 @@ fn index(req: HttpRequest) -> String {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource("/{name}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -104,7 +104,7 @@ You can also specify a custom regex in the form `{identifier:regex}`:
|
||||
# }
|
||||
#
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"{name:\d+}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -125,7 +125,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"/a/{v1}/{v2}/", |r| r.f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -143,7 +143,7 @@ It is possible to match path tail with custom `.*` regex.
|
||||
# unimplemented!()
|
||||
# }
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
@ -179,7 +179,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
|
@ -30,7 +30,7 @@ fn index(req: HttpRequest<AppState>) -> String {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::build("/", AppState{counter: Cell::new(0)})
|
||||
Application::with_state("/", AppState{counter: Cell::new(0)})
|
||||
.resource("/", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
Application::default("/")
|
||||
Application::new("/")
|
||||
.resource(r"/a/{name}", |r| r.method(Method::GET).f(index))
|
||||
.finish();
|
||||
}
|
||||
|
@ -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() {
|
||||
|
@ -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
|
||||
{
|
||||
|
@ -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;
|
||||
|
@ -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,
|
||||
}
|
||||
|
@ -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();
|
||||
/// }
|
||||
/// ```
|
||||
|
@ -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
|
||||
|
@ -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")
|
||||
|
@ -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();
|
||||
|
@ -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('/') {
|
||||
|
@ -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)
|
||||
/// ```
|
||||
|
@ -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,
|
||||
|
@ -42,7 +42,7 @@
|
||||
//! }
|
||||
//!
|
||||
//! fn main() {
|
||||
//! Application::default("/")
|
||||
//! Application::new("/")
|
||||
//! .resource("/ws/", |r| r.method(Method::GET).f(ws_index)) // <- register websocket route
|
||||
//! .finish();
|
||||
//! }
|
||||
|
@ -11,20 +11,13 @@ use tokio_core::net::TcpListener;
|
||||
use actix::*;
|
||||
use actix_web::*;
|
||||
|
||||
|
||||
fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
||||
HttpServer::new(
|
||||
vec![Application::default("/")
|
||||
.resource("/", |r|
|
||||
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
||||
.finish()])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serve() {
|
||||
thread::spawn(|| {
|
||||
let sys = System::new("test");
|
||||
let srv = create_server();
|
||||
let srv = HttpServer::new(
|
||||
vec![Application::new("/")
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))]);
|
||||
srv.serve::<_, ()>("127.0.0.1:58902").unwrap();
|
||||
sys.run();
|
||||
});
|
||||
@ -42,7 +35,9 @@ fn test_serve_incoming() {
|
||||
thread::spawn(move || {
|
||||
let sys = System::new("test");
|
||||
|
||||
let srv = create_server();
|
||||
let srv = HttpServer::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()).unwrap();
|
||||
sys.run();
|
||||
@ -89,19 +84,17 @@ fn test_middlewares() {
|
||||
let sys = System::new("test");
|
||||
|
||||
HttpServer::new(
|
||||
vec![Application::default("/")
|
||||
vec![Application::new("/")
|
||||
.middleware(MiddlewareTest{start: act_num1,
|
||||
response: act_num2,
|
||||
finish: act_num3})
|
||||
.resource("/", |r|
|
||||
r.route().method(Method::GET).h(httpcodes::HTTPOk))
|
||||
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))
|
||||
.finish()])
|
||||
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
||||
sys.run();
|
||||
});
|
||||
|
||||
assert!(reqwest::get("http://localhost:58904/").unwrap().status().is_success());
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
|
Loading…
Reference in New Issue
Block a user