1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

update to alpha2

This commit is contained in:
Nikolay Kim
2019-03-30 09:12:42 -07:00
parent 26f7c40d5e
commit 9a80911b92
40 changed files with 106 additions and 147 deletions

View File

@ -1,19 +1,8 @@
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]
extern crate prost_derive;
use actix_web::{
http, middleware, server, App, AsyncResponder, Error, HttpRequest, HttpResponse,
};
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use futures::Future;
mod protobuf;
use protobuf::ProtoBufResponseBuilder;
@ -26,31 +15,24 @@ pub struct MyObj {
}
/// This handler uses `ProtoBufMessage` for loading protobuf object.
fn index(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
protobuf::ProtoBufMessage::new(req)
fn index(pl: web::Payload) -> impl Future<Item = HttpResponse, Error = Error> {
protobuf::ProtoBufMessage::new(pl)
.from_err() // convert all errors into `Error`
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Ok(HttpResponse::Ok().protobuf(val)?) // <- send response
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info,actix_server=info");
env_logger::init();
let sys = actix::System::new("protobuf-example");
server::new(|| {
HttpServer::new(|| {
App::new()
.middleware(middleware::Logger::default())
.resource("/", |r| r.method(http::Method::POST).f(index))
.wrap(middleware::Logger::default())
.service(web::resource("/").route(web::post().to_async(index)))
})
.bind("127.0.0.1:8080")
.unwrap()
.shutdown_timeout(1)
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
.bind("127.0.0.1:8080")?
.run()
}

View File

@ -1,7 +1,8 @@
use bytes::BytesMut;
use futures::{Future, Poll, Stream};
use bytes::IntoBuf;
use bytes::{Bytes, IntoBuf};
use derive_more::{Display, From};
use prost::DecodeError as ProtoBufDecodeError;
use prost::EncodeError as ProtoBufEncodeError;
use prost::Message;
@ -9,25 +10,25 @@ use prost::Message;
use actix_web::dev::HttpResponseBuilder;
use actix_web::error::{Error, PayloadError, ResponseError};
use actix_web::http::header::CONTENT_TYPE;
use actix_web::{HttpMessage, HttpRequest, HttpResponse, Responder};
use actix_web::{HttpRequest, HttpResponse, Responder};
#[derive(Fail, Debug)]
#[derive(Debug, Display, From)]
pub enum ProtoBufPayloadError {
/// Payload size is bigger than 256k
#[fail(display = "Payload size is bigger than 256k")]
#[display(fmt = "Payload size is bigger than 256k")]
Overflow,
/// Content type error
#[fail(display = "Content type error")]
#[display(fmt = "Content type error")]
ContentType,
/// Serialize error
#[fail(display = "ProtoBud serialize error: {}", _0)]
Serialize(#[cause] ProtoBufEncodeError),
#[display(fmt = "ProtoBud serialize error: {}", _0)]
Serialize(ProtoBufEncodeError),
/// Deserialize error
#[fail(display = "ProtoBud deserialize error: {}", _0)]
Deserialize(#[cause] ProtoBufDecodeError),
#[display(fmt = "ProtoBud deserialize error: {}", _0)]
Deserialize(ProtoBufDecodeError),
/// Payload error
#[fail(display = "Error that occur during reading payload: {}", _0)]
Payload(#[cause] PayloadError),
#[display(fmt = "Error that occur during reading payload: {}", _0)]
Payload(PayloadError),
}
impl ResponseError for ProtoBufPayloadError {
@ -39,26 +40,14 @@ impl ResponseError for ProtoBufPayloadError {
}
}
impl From<PayloadError> for ProtoBufPayloadError {
fn from(err: PayloadError) -> ProtoBufPayloadError {
ProtoBufPayloadError::Payload(err)
}
}
impl From<ProtoBufDecodeError> for ProtoBufPayloadError {
fn from(err: ProtoBufDecodeError) -> ProtoBufPayloadError {
ProtoBufPayloadError::Deserialize(err)
}
}
#[derive(Debug)]
pub struct ProtoBuf<T: Message>(pub T);
impl<T: Message> Responder for ProtoBuf<T> {
type Item = HttpResponse;
type Error = Error;
type Future = Result<HttpResponse, Error>;
fn respond_to<S>(self, _: &HttpRequest<S>) -> Result<HttpResponse, Error> {
fn respond_to(self, _: &HttpRequest) -> Result<HttpResponse, Error> {
let mut buf = Vec::new();
self.0
.encode(&mut buf)
@ -78,9 +67,11 @@ pub struct ProtoBufMessage<U: Message + Default> {
impl<U: Message + Default + 'static> ProtoBufMessage<U> {
/// Create `ProtoBufMessage` for request.
pub fn new(req: &HttpRequest) -> Self {
let fut = req
.payload()
pub fn new<S>(pl: S) -> Self
where
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
{
let fut = pl
.map_err(|e| ProtoBufPayloadError::Payload(e))
.fold(BytesMut::new(), move |mut body, chunk| {
body.extend_from_slice(&chunk);