mirror of
https://github.com/actix/actix-web.git
synced 2025-01-08 16:25:29 +00:00
simplify Handler trait
This commit is contained in:
parent
27035c9454
commit
d2eae3d5b3
5 changed files with 23 additions and 25 deletions
|
@ -71,7 +71,7 @@ fn main() {
|
||||||
|
|
||||||
## Handler
|
## Handler
|
||||||
|
|
||||||
A request handler can have several different forms.
|
A request handler can have different forms.
|
||||||
|
|
||||||
* Simple function that accepts `HttpRequest` and returns `HttpResponse` or any
|
* Simple function that accepts `HttpRequest` and returns `HttpResponse` or any
|
||||||
type that can be converted into `HttpResponse`.
|
type that can be converted into `HttpResponse`.
|
||||||
|
|
|
@ -34,6 +34,7 @@ impl<S: 'static> Application<S> {
|
||||||
} else {
|
} else {
|
||||||
for (prefix, handler) in &self.handlers {
|
for (prefix, handler) in &self.handlers {
|
||||||
if req.path().starts_with(prefix) {
|
if req.path().starts_with(prefix) {
|
||||||
|
req.set_prefix(prefix.len());
|
||||||
handler.handle(req, task);
|
handler.handle(req, task);
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -232,7 +233,6 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
||||||
|
|
||||||
for (path, mut handler) in parts.handlers {
|
for (path, mut handler) in parts.handlers {
|
||||||
let path = prefix.clone() + path.trim_left_matches('/');
|
let path = prefix.clone() + path.trim_left_matches('/');
|
||||||
handler.set_prefix(path.clone());
|
|
||||||
handlers.insert(path, handler);
|
handlers.insert(path, handler);
|
||||||
}
|
}
|
||||||
Application {
|
Application {
|
||||||
|
|
|
@ -19,6 +19,7 @@ struct HttpMessage {
|
||||||
version: Version,
|
version: Version,
|
||||||
method: Method,
|
method: Method,
|
||||||
path: String,
|
path: String,
|
||||||
|
prefix: usize,
|
||||||
query: String,
|
query: String,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
extensions: Extensions,
|
extensions: Extensions,
|
||||||
|
@ -35,6 +36,7 @@ impl Default for HttpMessage {
|
||||||
HttpMessage {
|
HttpMessage {
|
||||||
method: Method::GET,
|
method: Method::GET,
|
||||||
path: String::new(),
|
path: String::new(),
|
||||||
|
prefix: 0,
|
||||||
query: String::new(),
|
query: String::new(),
|
||||||
version: Version::HTTP_11,
|
version: Version::HTTP_11,
|
||||||
headers: HeaderMap::new(),
|
headers: HeaderMap::new(),
|
||||||
|
@ -61,6 +63,7 @@ impl HttpRequest<()> {
|
||||||
Rc::new(HttpMessage {
|
Rc::new(HttpMessage {
|
||||||
method: method,
|
method: method,
|
||||||
path: path,
|
path: path,
|
||||||
|
prefix: 0,
|
||||||
query: query,
|
query: query,
|
||||||
version: version,
|
version: version,
|
||||||
headers: headers,
|
headers: headers,
|
||||||
|
@ -123,6 +126,15 @@ impl<S> HttpRequest<S> {
|
||||||
&self.0.path
|
&self.0.path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_prefix(&mut self, idx: usize) {
|
||||||
|
self.as_mut().prefix = idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn prefix_len(&self) -> usize {
|
||||||
|
self.0.prefix
|
||||||
|
}
|
||||||
|
|
||||||
/// Remote IP of client initiated HTTP request.
|
/// Remote IP of client initiated HTTP request.
|
||||||
///
|
///
|
||||||
/// The IP is resolved through the following headers, in this order:
|
/// The IP is resolved through the following headers, in this order:
|
||||||
|
|
12
src/route.rs
12
src/route.rs
|
@ -30,13 +30,12 @@ impl Frame {
|
||||||
/// Trait defines object that could be regestered as route handler
|
/// Trait defines object that could be regestered as route handler
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
pub trait Handler<S>: 'static {
|
pub trait Handler<S>: 'static {
|
||||||
|
|
||||||
|
/// The type of value that handler will return.
|
||||||
type Result: Into<Reply>;
|
type Result: Into<Reply>;
|
||||||
|
|
||||||
/// Handle request
|
/// Handle request
|
||||||
fn handle(&self, req: HttpRequest<S>) -> Self::Result;
|
fn handle(&self, req: HttpRequest<S>) -> Self::Result;
|
||||||
|
|
||||||
/// Set route prefix
|
|
||||||
fn set_prefix(&mut self, prefix: String) {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handler<S> for Fn()
|
/// Handler<S> for Fn()
|
||||||
|
@ -124,9 +123,6 @@ impl<A: Actor<Context=HttpContext<A, S>>, S: 'static> From<HttpContext<A, S>> fo
|
||||||
pub(crate) trait RouteHandler<S>: 'static {
|
pub(crate) trait RouteHandler<S>: 'static {
|
||||||
/// Handle request
|
/// Handle request
|
||||||
fn handle(&self, req: HttpRequest<S>, task: &mut Task);
|
fn handle(&self, req: HttpRequest<S>, task: &mut Task);
|
||||||
|
|
||||||
/// Set route prefix
|
|
||||||
fn set_prefix(&mut self, _prefix: String) {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Route handler wrapper for Handler
|
/// Route handler wrapper for Handler
|
||||||
|
@ -158,10 +154,6 @@ impl<S, H, R> RouteHandler<S> for WrapHandler<S, H, R>
|
||||||
fn handle(&self, req: HttpRequest<S>, task: &mut Task) {
|
fn handle(&self, req: HttpRequest<S>, task: &mut Task) {
|
||||||
self.h.handle(req).into().into(task)
|
self.h.handle(req).into().into(task)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_prefix(&mut self, prefix: String) {
|
|
||||||
self.h.set_prefix(prefix)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Async route handler
|
/// Async route handler
|
||||||
|
|
|
@ -33,7 +33,6 @@ pub struct StaticFiles {
|
||||||
_show_index: bool,
|
_show_index: bool,
|
||||||
_chunk_size: usize,
|
_chunk_size: usize,
|
||||||
_follow_symlinks: bool,
|
_follow_symlinks: bool,
|
||||||
prefix: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StaticFiles {
|
impl StaticFiles {
|
||||||
|
@ -65,12 +64,11 @@ impl StaticFiles {
|
||||||
_show_index: index,
|
_show_index: index,
|
||||||
_chunk_size: 0,
|
_chunk_size: 0,
|
||||||
_follow_symlinks: false,
|
_follow_symlinks: false,
|
||||||
prefix: String::new(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn index(&self, relpath: &str, filename: &PathBuf) -> Result<HttpResponse, io::Error> {
|
fn index(&self, prefix: &str, relpath: &str, filename: &PathBuf) -> Result<HttpResponse, io::Error> {
|
||||||
let index_of = format!("Index of {}/{}", self.prefix, relpath);
|
let index_of = format!("Index of {}{}", prefix, relpath);
|
||||||
let mut body = String::new();
|
let mut body = String::new();
|
||||||
|
|
||||||
for entry in filename.read_dir()? {
|
for entry in filename.read_dir()? {
|
||||||
|
@ -78,7 +76,7 @@ impl StaticFiles {
|
||||||
let entry = entry.unwrap();
|
let entry = entry.unwrap();
|
||||||
// show file url as relative to static path
|
// show file url as relative to static path
|
||||||
let file_url = format!(
|
let file_url = format!(
|
||||||
"{}/{}", self.prefix,
|
"{}{}", prefix,
|
||||||
entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy());
|
entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy());
|
||||||
|
|
||||||
// if file is a directory, add '/' to the end of the name
|
// if file is a directory, add '/' to the end of the name
|
||||||
|
@ -130,18 +128,12 @@ impl StaticFiles {
|
||||||
impl<S> Handler<S> for StaticFiles {
|
impl<S> Handler<S> for StaticFiles {
|
||||||
type Result = Result<HttpResponse, io::Error>;
|
type Result = Result<HttpResponse, io::Error>;
|
||||||
|
|
||||||
fn set_prefix(&mut self, prefix: String) {
|
|
||||||
if prefix != "/" {
|
|
||||||
self.prefix += &prefix;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn handle(&self, req: HttpRequest<S>) -> Self::Result {
|
fn handle(&self, req: HttpRequest<S>) -> Self::Result {
|
||||||
if !self.accessible {
|
if !self.accessible {
|
||||||
Ok(HTTPNotFound.into())
|
Ok(HTTPNotFound.into())
|
||||||
} else {
|
} else {
|
||||||
let mut hidden = false;
|
let mut hidden = false;
|
||||||
let filepath = req.path()[self.prefix.len()..]
|
let filepath = req.path()[req.prefix_len()..]
|
||||||
.split('/').filter(|s| {
|
.split('/').filter(|s| {
|
||||||
if s.starts_with('.') {
|
if s.starts_with('.') {
|
||||||
hidden = true;
|
hidden = true;
|
||||||
|
@ -167,7 +159,9 @@ impl<S> Handler<S> for StaticFiles {
|
||||||
};
|
};
|
||||||
|
|
||||||
if filename.is_dir() {
|
if filename.is_dir() {
|
||||||
match self.index(&filepath[idx..], &filename) {
|
match self.index(
|
||||||
|
&req.path()[..req.prefix_len()], &filepath[idx..], &filename)
|
||||||
|
{
|
||||||
Ok(resp) => Ok(resp),
|
Ok(resp) => Ok(resp),
|
||||||
Err(err) => match err.kind() {
|
Err(err) => match err.kind() {
|
||||||
io::ErrorKind::NotFound => Ok(HTTPNotFound.into()),
|
io::ErrorKind::NotFound => Ok(HTTPNotFound.into()),
|
||||||
|
|
Loading…
Reference in a new issue