1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-12 18:29:34 +00:00
actix-web/src/route.rs
2017-10-06 23:36:36 -07:00

90 lines
2 KiB
Rust

use std::rc::Rc;
use std::marker::PhantomData;
use actix::Actor;
use bytes::Bytes;
use futures::unsync::mpsc::Receiver;
use task::Task;
use context::HttpContext;
use resource::HttpMessage;
use httpmessage::{HttpRequest, HttpResponse, IntoHttpResponse};
/// Stream of `PayloadItem`'s
pub type Payload = Receiver<PayloadItem>;
/// `PayloadItem` represents one payload item
#[derive(Debug)]
pub enum PayloadItem {
/// Indicates end of payload stream
Eof,
/// Chunk of bytes
Chunk(Bytes)
}
impl PayloadItem {
/// Is item an eof
pub fn is_eof(&self) -> bool {
match *self {
PayloadItem::Eof => true,
_ => false,
}
}
/// Is item a chunk
pub fn is_chunk(&self) -> bool {
!self.is_eof()
}
}
#[doc(hidden)]
#[derive(Debug)]
#[cfg_attr(feature="cargo-clippy", allow(large_enum_variant))]
pub enum Frame {
Message(HttpResponse),
Payload(Option<Bytes>),
}
pub trait RouteHandler<S>: 'static {
fn handle(&self, req: HttpRequest, payload: Option<Payload>, state: Rc<S>) -> Task;
}
/// Actors with ability to handle http requests
pub trait Route: Actor<Context=HttpContext<Self>> {
type State;
fn request(req: HttpRequest,
payload: Option<Payload>,
ctx: &mut HttpContext<Self>) -> HttpMessage<Self>;
fn factory() -> RouteFactory<Self, Self::State> {
RouteFactory(PhantomData)
}
/// Create async response
fn stream(act: Self) -> HttpMessage<Self> {
HttpMessage::stream(act)
}
/// Create response
fn reply<I>(req: HttpRequest, msg: I) -> HttpMessage<Self>
where I: IntoHttpResponse
{
HttpMessage::reply(req, msg)
}
}
pub struct RouteFactory<A: Route<State=S>, S>(PhantomData<A>);
impl<A, S> RouteHandler<S> for RouteFactory<A, S>
where A: Route<State=S>,
S: 'static
{
fn handle(&self, req: HttpRequest, payload: Option<Payload>, state: Rc<A::State>) -> Task
{
let mut ctx = HttpContext::new(state);
A::request(req, payload, &mut ctx).into(ctx)
}
}