use std::marker::PhantomData; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_http::error::{Error, ResponseError}; use actix_http::ws::{verify_handshake, HandshakeError}; use actix_http::{h1, Request}; use actix_service::{NewService, Service}; use futures::future::{ok, Either, FutureResult}; use futures::{Async, Future, IntoFuture, Poll}; /// Service that verifies incoming request if it is valid websocket /// upgrade request. In case of error returns `HandshakeError` pub struct VerifyWebSockets { _t: PhantomData, } impl Default for VerifyWebSockets { fn default() -> Self { VerifyWebSockets { _t: PhantomData } } } impl NewService for VerifyWebSockets { type Request = (Request, Framed); type Response = (Request, Framed); type Error = (HandshakeError, Framed); type InitError = (); type Service = VerifyWebSockets; type Future = FutureResult; fn new_service(&self, _: &()) -> Self::Future { ok(VerifyWebSockets { _t: PhantomData }) } } impl Service for VerifyWebSockets { type Request = (Request, Framed); type Response = (Request, Framed); type Error = (HandshakeError, Framed); type Future = FutureResult; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(Async::Ready(())) } fn call(&mut self, (req, framed): (Request, Framed)) -> Self::Future { match verify_handshake(req.head()) { Err(e) => Err((e, framed)).into_future(), Ok(_) => Ok((req, framed)).into_future(), } } } /// Send http/1 error response pub struct SendError(PhantomData<(T, R, E)>); impl Default for SendError where T: AsyncRead + AsyncWrite, E: ResponseError, { fn default() -> Self { SendError(PhantomData) } } impl NewService for SendError where T: AsyncRead + AsyncWrite + 'static, R: 'static, E: ResponseError + 'static, { type Request = Result)>; type Response = R; type Error = Error; type InitError = (); type Service = SendError; type Future = FutureResult; fn new_service(&self, _: &()) -> Self::Future { ok(SendError(PhantomData)) } } impl Service for SendError where T: AsyncRead + AsyncWrite + 'static, R: 'static, E: ResponseError + 'static, { type Request = Result)>; type Response = R; type Error = Error; type Future = Either, Box>>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(Async::Ready(())) } fn call(&mut self, req: Result)>) -> Self::Future { match req { Ok(r) => Either::A(ok(r)), Err((e, framed)) => { let res = e.render_response(); let e = Error::from(e); Either::B(Box::new( h1::SendResponse::new(framed, res).then(move |_| Err(e)), )) } } } }