mirror of
https://github.com/actix/examples
synced 2025-06-26 17:17:42 +02:00
upgrade actix-web to 0.6
This commit is contained in:
@ -9,26 +9,23 @@ extern crate prost;
|
||||
#[macro_use]
|
||||
extern crate prost_derive;
|
||||
|
||||
use actix_web::{http, middleware, server, App, AsyncResponder, Error, HttpRequest,
|
||||
HttpResponse};
|
||||
use futures::Future;
|
||||
use actix_web::{
|
||||
http, middleware, server,
|
||||
App, AsyncResponder, HttpRequest, HttpResponse, Error};
|
||||
|
||||
mod protobuf;
|
||||
use protobuf::ProtoBufResponseBuilder;
|
||||
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Message)]
|
||||
pub struct MyObj {
|
||||
#[prost(int32, tag="1")]
|
||||
#[prost(int32, tag = "1")]
|
||||
pub number: i32,
|
||||
#[prost(string, tag="2")]
|
||||
#[prost(string, tag = "2")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
|
||||
/// This handler uses `ProtoBufMessage` for loading protobuf object.
|
||||
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
fn index(req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
|
||||
protobuf::ProtoBufMessage::new(req)
|
||||
.from_err() // convert all errors into `Error`
|
||||
.and_then(|val: MyObj| {
|
||||
@ -38,7 +35,6 @@ fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
.responder()
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
::std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
@ -47,8 +43,9 @@ fn main() {
|
||||
server::new(|| {
|
||||
App::new()
|
||||
.middleware(middleware::Logger::default())
|
||||
.resource("/", |r| r.method(http::Method::POST).f(index))})
|
||||
.bind("127.0.0.1:8080").unwrap()
|
||||
.resource("/", |r| r.method(http::Method::POST).f(index))
|
||||
}).bind("127.0.0.1:8080")
|
||||
.unwrap()
|
||||
.shutdown_timeout(1)
|
||||
.start();
|
||||
|
||||
|
@ -1,38 +1,36 @@
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::{Poll, Future, Stream};
|
||||
use futures::{Future, Poll, Stream};
|
||||
|
||||
use bytes::IntoBuf;
|
||||
use prost::Message;
|
||||
use prost::DecodeError as ProtoBufDecodeError;
|
||||
use prost::EncodeError as ProtoBufEncodeError;
|
||||
use prost::Message;
|
||||
|
||||
use actix_web::http::header::{CONTENT_TYPE, CONTENT_LENGTH};
|
||||
use actix_web::{Responder, HttpMessage, HttpRequest, HttpResponse};
|
||||
use actix_web::dev::HttpResponseBuilder;
|
||||
use actix_web::error::{Error, PayloadError, ResponseError};
|
||||
|
||||
use actix_web::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
|
||||
use actix_web::{HttpMessage, HttpRequest, HttpResponse, Responder};
|
||||
|
||||
#[derive(Fail, Debug)]
|
||||
pub enum ProtoBufPayloadError {
|
||||
/// Payload size is bigger than 256k
|
||||
#[fail(display="Payload size is bigger than 256k")]
|
||||
#[fail(display = "Payload size is bigger than 256k")]
|
||||
Overflow,
|
||||
/// Content type error
|
||||
#[fail(display="Content type error")]
|
||||
#[fail(display = "Content type error")]
|
||||
ContentType,
|
||||
/// Serialize error
|
||||
#[fail(display="ProtoBud serialize error: {}", _0)]
|
||||
#[fail(display = "ProtoBud serialize error: {}", _0)]
|
||||
Serialize(#[cause] ProtoBufEncodeError),
|
||||
/// Deserialize error
|
||||
#[fail(display="ProtoBud deserialize error: {}", _0)]
|
||||
#[fail(display = "ProtoBud deserialize error: {}", _0)]
|
||||
Deserialize(#[cause] ProtoBufDecodeError),
|
||||
/// Payload error
|
||||
#[fail(display="Error that occur during reading payload: {}", _0)]
|
||||
#[fail(display = "Error that occur during reading payload: {}", _0)]
|
||||
Payload(#[cause] PayloadError),
|
||||
}
|
||||
|
||||
impl ResponseError for ProtoBufPayloadError {
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
ProtoBufPayloadError::Overflow => HttpResponse::PayloadTooLarge().into(),
|
||||
@ -60,31 +58,31 @@ impl<T: Message> Responder for ProtoBuf<T> {
|
||||
type Item = HttpResponse;
|
||||
type Error = Error;
|
||||
|
||||
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
|
||||
fn respond_to<S>(self, _: &HttpRequest<S>) -> Result<HttpResponse, Error> {
|
||||
let mut buf = Vec::new();
|
||||
self.0.encode(&mut buf)
|
||||
self.0
|
||||
.encode(&mut buf)
|
||||
.map_err(|e| Error::from(ProtoBufPayloadError::Serialize(e)))
|
||||
.and_then(|()| {
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/protobuf")
|
||||
.content_type("application/protobuf")
|
||||
.body(buf)
|
||||
.into())
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProtoBufMessage<T, U: Message + Default>{
|
||||
pub struct ProtoBufMessage<T, U: Message + Default> {
|
||||
limit: usize,
|
||||
ct: &'static str,
|
||||
req: Option<T>,
|
||||
fut: Option<Box<Future<Item=U, Error=ProtoBufPayloadError>>>,
|
||||
fut: Option<Box<Future<Item = U, Error = ProtoBufPayloadError>>>,
|
||||
}
|
||||
|
||||
impl<T, U: Message + Default> ProtoBufMessage<T, U> {
|
||||
|
||||
/// Create `ProtoBufMessage` for request.
|
||||
pub fn new(req: T) -> Self {
|
||||
ProtoBufMessage{
|
||||
ProtoBufMessage {
|
||||
limit: 262_144,
|
||||
req: Some(req),
|
||||
fut: None,
|
||||
@ -109,7 +107,8 @@ impl<T, U: Message + Default> ProtoBufMessage<T, U> {
|
||||
}
|
||||
|
||||
impl<T, U: Message + Default + 'static> Future for ProtoBufMessage<T, U>
|
||||
where T: HttpMessage + Stream<Item=Bytes, Error=PayloadError> + 'static
|
||||
where
|
||||
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
||||
{
|
||||
type Item = U;
|
||||
type Error = ProtoBufPayloadError;
|
||||
@ -129,7 +128,7 @@ impl<T, U: Message + Default + 'static> Future for ProtoBufMessage<T, U>
|
||||
}
|
||||
// check content-type
|
||||
if !self.ct.is_empty() && req.content_type() != self.ct {
|
||||
return Err(ProtoBufPayloadError::ContentType)
|
||||
return Err(ProtoBufPayloadError::ContentType);
|
||||
}
|
||||
|
||||
let limit = self.limit;
|
||||
@ -146,23 +145,25 @@ impl<T, U: Message + Default + 'static> Future for ProtoBufMessage<T, U>
|
||||
self.fut = Some(Box::new(fut));
|
||||
}
|
||||
|
||||
self.fut.as_mut().expect("ProtoBufBody could not be used second time").poll()
|
||||
self.fut
|
||||
.as_mut()
|
||||
.expect("ProtoBufBody could not be used second time")
|
||||
.poll()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub trait ProtoBufResponseBuilder {
|
||||
|
||||
fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
|
||||
}
|
||||
|
||||
impl ProtoBufResponseBuilder for HttpResponseBuilder {
|
||||
|
||||
fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
|
||||
self.header(CONTENT_TYPE, "application/protobuf");
|
||||
|
||||
let mut body = Vec::new();
|
||||
value.encode(&mut body).map_err(|e| ProtoBufPayloadError::Serialize(e))?;
|
||||
value
|
||||
.encode(&mut body)
|
||||
.map_err(|e| ProtoBufPayloadError::Serialize(e))?;
|
||||
Ok(self.body(body))
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user