1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-02-07 22:04:24 +01:00

58 lines
1.4 KiB
Rust
Raw Normal View History

2018-03-09 10:05:13 +08:00
extern crate actix;
extern crate actix_web;
extern crate bytes;
extern crate futures;
2018-03-09 05:29:06 -08:00
#[macro_use]
extern crate failure;
2018-03-09 10:05:13 +08:00
extern crate env_logger;
extern crate prost;
2018-03-09 05:29:06 -08:00
#[macro_use]
2018-03-09 10:05:13 +08:00
extern crate prost_derive;
use futures::Future;
2018-03-30 18:54:38 -07:00
use actix_web::{
http, middleware, server,
2018-03-31 00:16:55 -07:00
App, AsyncResponder, HttpRequest, HttpResponse, Error};
2018-03-09 10:05:13 +08:00
2018-03-09 05:29:06 -08:00
mod protobuf;
use protobuf::ProtoBufResponseBuilder;
2018-03-09 10:05:13 +08:00
#[derive(Clone, Debug, PartialEq, Message)]
pub struct MyObj {
#[prost(int32, tag="1")]
pub number: i32,
#[prost(string, tag="2")]
pub name: String,
}
2018-03-09 05:29:06 -08:00
/// This handler uses `ProtoBufMessage` for loading protobuf object.
2018-03-09 10:05:13 +08:00
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
2018-03-09 05:29:06 -08:00
protobuf::ProtoBufMessage::new(req)
2018-03-09 10:05:13 +08:00
.from_err() // convert all errors into `Error`
.and_then(|val: MyObj| {
println!("model: {:?}", val);
2018-03-30 18:54:38 -07:00
Ok(HttpResponse::Ok().protobuf(val)?) // <- send response
2018-03-09 10:05:13 +08:00
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
2018-03-30 18:54:38 -07:00
env_logger::init();
2018-03-09 10:05:13 +08:00
let sys = actix::System::new("protobuf-example");
server::new(|| {
2018-03-31 00:16:55 -07:00
App::new()
2018-03-09 10:05:13 +08:00
.middleware(middleware::Logger::default())
2018-03-30 18:54:38 -07:00
.resource("/", |r| r.method(http::Method::POST).f(index))})
2018-03-09 10:05:13 +08:00
.bind("127.0.0.1:8080").unwrap()
.shutdown_timeout(1)
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}