1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-21 09:23:54 +00:00
actix-web/src/route.rs

62 lines
1.9 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::marker::PhantomData;
use actix::Actor;
use bytes::Bytes;
use task::Task;
use context::HttpContext;
2017-10-08 21:56:51 +00:00
use resource::Reply;
2017-10-09 03:16:48 +00:00
use payload::Payload;
use httprequest::HttpRequest;
2017-10-15 16:33:17 +00:00
use httpresponse::HttpResponse;
2017-10-07 04:48:14 +00:00
2017-10-07 06:14:13 +00:00
#[doc(hidden)]
2017-10-07 04:48:14 +00:00
#[derive(Debug)]
#[cfg_attr(feature="cargo-clippy", allow(large_enum_variant))]
pub enum Frame {
Message(HttpResponse),
2017-10-07 04:48:14 +00:00
Payload(Option<Bytes>),
}
2017-10-08 21:56:51 +00:00
/// Trait defines object that could be regestered as resource route
2017-10-07 04:48:14 +00:00
pub trait RouteHandler<S>: 'static {
2017-10-10 06:07:32 +00:00
/// Handle request
2017-10-09 03:16:48 +00:00
fn handle(&self, req: HttpRequest, payload: Payload, state: Rc<S>) -> Task;
2017-10-10 06:07:32 +00:00
/// Set route prefix
fn set_prefix(&mut self, _prefix: String) {}
2017-10-07 04:48:14 +00:00
}
2017-10-07 06:14:13 +00:00
/// Actors with ability to handle http requests
2017-10-10 06:07:32 +00:00
pub trait Route: Actor {
2017-10-08 06:59:57 +00:00
/// Route shared state. State is shared with all routes within same application and could be
/// accessed with `HttpContext::state()` method.
2017-10-07 04:48:14 +00:00
type State;
2017-10-08 06:59:57 +00:00
/// Handle incoming request. Route actor can return
2017-10-08 21:56:51 +00:00
/// result immediately with `Reply::reply` or `Reply::with`.
2017-10-08 06:59:57 +00:00
/// Actor itself could be returned for handling streaming request/response.
2017-10-08 21:56:51 +00:00
/// In that case `HttpContext::start` and `HttpContext::write` has to be used.
2017-10-10 06:07:32 +00:00
fn request(req: HttpRequest, payload: Payload, ctx: &mut Self::Context) -> Reply<Self>;
2017-10-07 04:48:14 +00:00
2017-10-08 06:59:57 +00:00
/// This method creates `RouteFactory` for this actor.
2017-10-07 04:48:14 +00:00
fn factory() -> RouteFactory<Self, Self::State> {
RouteFactory(PhantomData)
}
}
2017-10-08 21:56:51 +00:00
/// This is used for routes registration within `Resource`
2017-10-07 04:48:14 +00:00
pub struct RouteFactory<A: Route<State=S>, S>(PhantomData<A>);
impl<A, S> RouteHandler<S> for RouteFactory<A, S>
2017-10-10 06:07:32 +00:00
where A: Actor<Context=HttpContext<A>> + Route<State=S>,
2017-10-07 04:48:14 +00:00
S: 'static
{
2017-10-09 03:16:48 +00:00
fn handle(&self, req: HttpRequest, payload: Payload, state: Rc<A::State>) -> Task
2017-10-07 04:48:14 +00:00
{
2017-10-07 06:14:13 +00:00
let mut ctx = HttpContext::new(state);
2017-10-07 04:48:14 +00:00
A::request(req, payload, &mut ctx).into(ctx)
}
}