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

upgrade diesel, r2d2, state examples

This commit is contained in:
Nikolay Kim
2019-03-07 14:50:29 -08:00
parent 60a9df8abd
commit f39a53ea3a
10 changed files with 185 additions and 282 deletions

View File

@ -2,9 +2,12 @@
name = "json-example"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = "../"
workspace = ".."
edition = "2018"
[dependencies]
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
bytes = "0.4"
futures = "0.1"
env_logger = "*"
@ -13,6 +16,3 @@ serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"
json = "*"
actix = "0.7"
actix-web = "^0.7"

View File

@ -1,22 +1,13 @@
extern crate actix;
extern crate actix_web;
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate json;
use actix_web::{
error, http, middleware, server, App, AsyncResponder, Error, HttpMessage,
HttpRequest, HttpResponse, Json,
error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
};
use bytes::BytesMut;
use bytes::{Bytes, BytesMut};
use futures::{Future, Stream};
use json::JsonValue;
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct MyObj {
@ -24,39 +15,34 @@ struct MyObj {
number: i32,
}
/// This handler uses `HttpRequest::json()` for loading json object.
fn index(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
req.json()
.from_err() // convert all errors into `Error`
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Ok(HttpResponse::Ok().json(val)) // <- send response
})
.responder()
}
/// This handler uses json extractor
fn extract_item(item: Json<MyObj>) -> HttpResponse {
fn index(item: web::Json<MyObj>) -> HttpResponse {
println!("model: {:?}", &item);
HttpResponse::Ok().json(item.0) // <- send response
}
/// This handler uses json extractor with limit
fn extract_item_limit((item, _req): (Json<MyObj>, HttpRequest)) -> HttpResponse {
println!("model: {:?}", &item);
HttpResponse::Ok().json(item.0) // <- send response
fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
println!("request: {:?}", req);
println!("model: {:?}", item);
HttpResponse::Ok().json(item.0) // <- send json response
}
const MAX_SIZE: usize = 262_144; // max payload size is 256k
/// This handler manually load request payload and parse json object
fn index_manual(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
// HttpRequest::payload() is stream of Bytes objects
req.payload()
fn index_manual<P>(
payload: web::Payload<P>,
) -> impl Future<Item = HttpResponse, Error = Error>
where
P: Stream<Item = Bytes, Error = error::PayloadError>,
{
// payload is a stream of Bytes objects
payload
// `Future::from_err` acts like `?` in that it coerces the error type from
// the future into the final error type
.from_err()
// `fold` will asynchronously read each chunk of the request body and
// call supplied closure, then it resolves to result of closure
.fold(BytesMut::new(), move |mut body, chunk| {
@ -75,59 +61,56 @@ fn index_manual(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Er
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(HttpResponse::Ok().json(obj)) // <- send response
})
.responder()
}
/// This handler manually load request payload and parse json-rust
fn index_mjsonrust(
req: &HttpRequest,
) -> Box<Future<Item = HttpResponse, Error = Error>> {
req.payload()
.concat2()
.from_err()
.and_then(|body| {
// body is loaded, now we can deserialize json-rust
let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
let injson: JsonValue = match result {
Ok(v) => v,
Err(e) => object!{"err" => e.to_string() },
};
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(injson.dump()))
})
.responder()
fn index_mjsonrust<P>(
pl: web::Payload<P>,
) -> impl Future<Item = HttpResponse, Error = Error>
where
P: Stream<Item = Bytes, Error = error::PayloadError>,
{
pl.concat2().from_err().and_then(|body| {
// body is loaded, now we can deserialize json-rust
let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
let injson: JsonValue = match result {
Ok(v) => v,
Err(e) => json::object! {"err" => e.to_string() },
};
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(injson.dump()))
})
}
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");
env_logger::init();
let sys = actix::System::new("json-example");
server::new(|| {
HttpServer::new(|| {
App::new()
// enable logger
.middleware(middleware::Logger::default())
.resource("/extractor", |r| {
r.method(http::Method::POST)
.with_config(extract_item, |(cfg,)| {
cfg.limit(4096); // <- limit size of the payload
})
})
.resource("/extractor2", |r| {
r.method(http::Method::POST)
.with_config(extract_item_limit, |((cfg, _),)| {
cfg.limit(4096); // <- limit size of the payload
})
})
.resource("/manual", |r| r.method(http::Method::POST).f(index_manual))
.resource("/mjsonrust", |r| r.method(http::Method::POST).f(index_mjsonrust))
.resource("/", |r| r.method(http::Method::POST).f(index))
}).bind("127.0.0.1:8080")
.unwrap()
.shutdown_timeout(1)
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
.service(
web::resource("/extractor").route(
web::post()
.config(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
.to(index),
),
)
.service(
web::resource("/extractor2").route(
web::post()
.config(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
.to_async(extract_item),
),
)
.service(web::resource("/manual").route(web::post().to_async(index_manual)))
.service(
web::resource("/mjsonrust").route(web::post().to_async(index_mjsonrust)),
)
.service(web::resource("/").route(web::post().to(index)))
})
.bind("127.0.0.1:8080")?
.run()
}