Skip to content

Commit

Permalink
move protobuf support to the example
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Mar 9, 2018
1 parent 2068eee commit 49e007f
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 44 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ script:
after_success:
- |
if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
cargo doc --features "alpn, tls, protobuf" --no-deps &&
cargo doc --features "alpn, tls" --no-deps &&
echo "<meta http-equiv=refresh content=0;url=os_balloon/index.html>" > target/doc/index.html &&
cargo install mdbook &&
cd guide && mdbook build -d ../target/doc/guide && cd .. &&
Expand Down
6 changes: 0 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,6 @@ alpn = ["openssl", "openssl/v102", "openssl/v110", "tokio-openssl"]
# sessions
session = ["cookie/secure"]

# protobuf
protobuf = ["prost"]

[dependencies]
actix = "^0.5.2"

Expand Down Expand Up @@ -90,9 +87,6 @@ tokio-tls = { version="0.1", optional = true }
openssl = { version="0.10", optional = true }
tokio-openssl = { version="0.2", optional = true }

# protobuf
prost = { version="^0.2", optional = true }

[dev-dependencies]
env_logger = "0.5"
skeptic = "0.13"
Expand Down
3 changes: 2 additions & 1 deletion examples/protobuf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ authors = ["kingxsp <[email protected]>"]
[dependencies]
bytes = "0.4"
futures = "0.1"
failure = "0.1"
env_logger = "*"

prost = "0.2.0"
prost-derive = "0.2.0"

actix = "0.5"
actix-web = { path="../../", features=["protobuf"] }
actix-web = { path="../../" }
12 changes: 8 additions & 4 deletions examples/protobuf/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ extern crate actix;
extern crate actix_web;
extern crate bytes;
extern crate futures;
#[macro_use]
extern crate failure;
extern crate env_logger;
extern crate prost;
#[macro_use]
#[macro_use]
extern crate prost_derive;

use actix_web::*;
use actix_web::ProtoBufBody;
use futures::Future;

mod protobuf;
use protobuf::ProtoBufResponseBuilder;


#[derive(Clone, Debug, PartialEq, Message)]
pub struct MyObj {
Expand All @@ -21,9 +25,9 @@ pub struct MyObj {
}


/// This handler uses `HttpRequest::json()` for loading serde json object.
/// This handler uses `ProtoBufMessage` for loading protobuf object.
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
ProtoBufBody::new(req)
protobuf::ProtoBufMessage::new(req)
.from_err() // convert all errors into `Error`
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Expand Down
51 changes: 27 additions & 24 deletions src/protobuf.rs → examples/protobuf/src/protobuf.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
use bytes::{Bytes, BytesMut};
use futures::{Poll, Future, Stream};
use http::header::{CONTENT_TYPE, CONTENT_LENGTH};

use bytes::IntoBuf;
use prost::Message;
use prost::EncodeError as ProtoBufEncodeError;
use prost::DecodeError as ProtoBufDecodeError;
use prost::EncodeError as ProtoBufEncodeError;

use actix_web::header::http::{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::httpcodes::{HttpBadRequest, HttpPayloadTooLarge};

use error::{Error, PayloadError, ResponseError};
use handler::Responder;
use httpmessage::HttpMessage;
use httprequest::HttpRequest;
use httpresponse::{HttpResponse, HttpResponseBuilder};
use httpcodes::{HttpBadRequest, HttpPayloadTooLarge};

#[derive(Fail, Debug)]
pub enum ProtoBufPayloadError {
Expand All @@ -22,8 +21,11 @@ pub enum ProtoBufPayloadError {
/// Content type error
#[fail(display="Content type error")]
ContentType,
/// Serialize error
#[fail(display="ProtoBud serialize error: {}", _0)]
Serialize(#[cause] ProtoBufEncodeError),
/// Deserialize error
#[fail(display="Json deserialize error: {}", _0)]
#[fail(display="ProtoBud deserialize error: {}", _0)]
Deserialize(#[cause] ProtoBufDecodeError),
/// Payload error
#[fail(display="Error that occur during reading payload: {}", _0)]
Expand Down Expand Up @@ -52,10 +54,6 @@ impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
}
}

/// `InternalServerError` for `ProtoBufEncodeError` `ProtoBufDecodeError`
impl ResponseError for ProtoBufEncodeError {}
impl ResponseError for ProtoBufDecodeError {}

#[derive(Debug)]
pub struct ProtoBuf<T: Message>(pub T);

Expand All @@ -66,28 +64,28 @@ impl<T: Message> Responder for ProtoBuf<T> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
let mut buf = Vec::new();
self.0.encode(&mut buf)
.map_err(Error::from)
.and_then(|()| {
.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 ProtoBufBody<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>>>,
}

impl<T, U: Message + Default> ProtoBufBody<T, U> {
impl<T, U: Message + Default> ProtoBufMessage<T, U> {

/// Create `ProtoBufBody` for request.
/// Create `ProtoBufMessage` for request.
pub fn new(req: T) -> Self {
ProtoBufBody{
ProtoBufMessage{
limit: 262_144,
req: Some(req),
fut: None,
Expand All @@ -111,7 +109,7 @@ impl<T, U: Message + Default> ProtoBufBody<T, U> {
}
}

impl<T, U: Message + Default + 'static> Future for ProtoBufBody<T, U>
impl<T, U: Message + Default + 'static> Future for ProtoBufMessage<T, U>
where T: HttpMessage + Stream<Item=Bytes, Error=PayloadError> + 'static
{
type Item = U;
Expand Down Expand Up @@ -154,13 +152,18 @@ impl<T, U: Message + Default + 'static> Future for ProtoBufBody<T, U>
}


impl HttpResponseBuilder {
pub trait ProtoBufResponseBuilder {

fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error>;
}

impl ProtoBufResponseBuilder for HttpResponseBuilder {

pub fn protobuf<T: Message>(&mut self, value: T) -> Result<HttpResponse, Error> {
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)?;
value.encode(&mut body).map_err(|e| ProtoBufPayloadError::Serialize(e))?;
Ok(self.body(body)?)
}
}
8 changes: 0 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,6 @@ extern crate h2 as http2;
extern crate trust_dns_resolver;
#[macro_use] extern crate actix;

#[cfg(feature="protobuf")]
extern crate prost;

#[cfg(test)]
#[macro_use] extern crate serde_derive;

Expand Down Expand Up @@ -121,11 +118,6 @@ mod param;
mod payload;
mod pipeline;

#[cfg(feature="protobuf")]
mod protobuf;
#[cfg(feature="protobuf")]
pub use protobuf::{ProtoBuf, ProtoBufBody};

pub mod client;
pub mod fs;
pub mod ws;
Expand Down

0 comments on commit 49e007f

Please sign in to comment.