1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

upgrade to alpha.6

This commit is contained in:
Nikolay Kim 2019-04-14 10:34:41 -07:00
parent 8fb2bf6869
commit 09b0188ff9
13 changed files with 93 additions and 117 deletions

View File

@ -12,7 +12,6 @@
// - POSTing json body
// 3. chaining futures into a single response used by an asynch endpoint
#[macro_use]
extern crate validator_derive;
#[macro_use]
@ -47,8 +46,6 @@ struct HttpBinResponse {
url: String,
}
/// post json to httpbin, get it back in the response body, return deserialized
fn step_x(
data: SomeData,
@ -93,12 +90,9 @@ fn main() -> io::Result<()> {
println!("Starting server at: {:?}", endpoint);
HttpServer::new(|| {
App::new()
.data(Client::default())
.service(
web::resource("/something")
.route(web::post().to_async(create_something)),
)
App::new().data(Client::default()).service(
web::resource("/something").route(web::post().to_async(create_something)),
)
})
.bind(endpoint)?
.run()

View File

@ -1,47 +1,36 @@
use actix_web::{error, web};
use bytes::Bytes;
use futures::Stream;
use crate::{
handlers::{
products,
parts
},
};
use crate::handlers::{parts, products};
pub fn config_app<P>(cfg: &mut web::RouterConfig<P>)
where P: Stream<Item = Bytes, Error = error::PayloadError>
+ 'static
{
pub fn config_app(cfg: &mut web::RouterConfig) {
// domain includes: /products/{product_id}/parts/{part_id}
cfg.service(
web::scope("/products")
.service(
web::resource("")
.route(web::get().to_async(products::get_products))
.route(web::post().to_async(products::add_product))
.route(web::post().to_async(products::add_product)),
)
.service(
web::scope("/{product_id}")
.service(
web::resource("")
.route(web::get().to_async(products::get_product_detail))
.route(web::delete().to_async(products::remove_product))
.route(web::delete().to_async(products::remove_product)),
)
.service(
web::scope("/parts")
.service(
web::resource("")
.route(web::get().to_async(parts::get_parts))
.route(web::post().to_async(parts::add_part))
.route(web::post().to_async(parts::add_part)),
)
.service(
web::resource("/{part_id}")
.route(web::get().to_async(parts::get_part_detail))
.route(web::delete().to_async(parts::remove_part))
)
)
)
.route(web::delete().to_async(parts::remove_part)),
),
),
),
);
}

View File

@ -1,19 +1,16 @@
use actix_web::{middleware, App, HttpServer};
use async_ex2::{
appconfig::config_app,
};
use async_ex2::appconfig::config_app;
fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
env_logger::init();
HttpServer::new(||
HttpServer::new(|| {
App::new()
.configure(config_app)
.wrap(middleware::Logger::default())
)
})
.bind("127.0.0.1:8080")?
.run()
}

View File

@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
pub struct Product {
id: Option<i64>,
@ -8,7 +7,6 @@ pub struct Product {
name: Option<String>,
}
#[derive(Deserialize, Serialize)]
pub struct Part {
id: Option<i64>,

View File

@ -1,3 +1,2 @@
pub mod products;
pub mod parts;
pub mod products;

View File

@ -1,26 +1,32 @@
use actix_multipart::{Field, Item, Multipart, MultipartError};
use actix_web::{HttpResponse, web, error, Error};
use futures::{future::{ok as fut_ok, err as fut_err, Either}, Future, Stream};
use actix_multipart::{Field, Multipart, MultipartError};
use actix_web::{error, web, Error, HttpResponse};
use futures::{
future::{err as fut_err, ok as fut_ok, Either},
Future, Stream,
};
use crate::common::{Part, Product};
pub fn get_parts(query: web::Query<Option<Part>>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn get_parts(
query: web::Query<Option<Part>>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn add_part(new_part: web::Json<Product>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn add_part(
new_part: web::Json<Product>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn get_part_detail(id: web::Path<String>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn get_part_detail(
id: web::Path<String>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn remove_part(id: web::Path<String>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn remove_part(
id: web::Path<String>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}

View File

@ -1,54 +1,57 @@
use actix_multipart::{Field, Item, Multipart, MultipartError};
use actix_web::{HttpResponse, web, error, Error};
use futures::{future::{ok as fut_ok, err as fut_err, Either}, Future, Stream};
use actix_multipart::{Field, Multipart, MultipartError};
use actix_web::{error, web, Error, HttpResponse};
use futures::{
future::{err as fut_err, ok as fut_ok, Either},
Future, Stream,
};
use crate::common::{Part, Product};
pub fn get_products(query: web::Query<Option<Part>>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn get_products(
query: web::Query<Option<Part>>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn add_product(new_product: web::Json<Product>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn add_product(
new_product: web::Json<Product>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn get_product_detail(id: web::Path<String>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn get_product_detail(
id: web::Path<String>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
pub fn remove_product(id: web::Path<String>)
-> impl Future<Item = HttpResponse, Error = Error> {
pub fn remove_product(
id: web::Path<String>,
) -> impl Future<Item = HttpResponse, Error = Error> {
fut_ok(HttpResponse::Ok().finish())
}
#[cfg(test)]
mod tests {
use super::*;
use actix_service::Service;
use actix_web::{test, HttpResponse, HttpRequest, App,
http::{header, StatusCode}, web};
use crate::appconfig::config_app;
use actix_service::Service;
use actix_web::{
http::{header, StatusCode},
test, web, App, HttpRequest, HttpResponse,
};
#[test]
fn test_add_product() {
let mut app = test::init_service(
App::new()
.configure(config_app)
);
let mut app = test::init_service(App::new().configure(config_app));
let payload = r#"{"id":12345,"product_type":"fancy","name":"test"}"#.as_bytes();
let req = test::TestRequest::post()
.uri("/products")
.header(header::CONTENT_TYPE, "application/json")
.set_payload(payload)
.to_request();
.uri("/products")
.header(header::CONTENT_TYPE, "application/json")
.set_payload(payload)
.to_request();
let resp = test::block_on(app.call(req)).unwrap();

View File

@ -124,16 +124,17 @@ fn main() -> io::Result<()> {
.finish()
})))
// default
.default_resource(|r| {
.default_service(
// 404 for GET request
r.route(web::get().to(p404))
web::resource("")
.route(web::get().to(p404))
// all requests that are not `GET`
.route(
web::route()
.guard(guard::Not(guard::Get()))
.to(|| HttpResponse::MethodNotAllowed()),
)
})
),
)
})
.bind("127.0.0.1:8080")?
.start();

View File

@ -98,7 +98,7 @@ fn main() -> std::io::Result<()> {
App::new()
.data(forward_url.clone())
.wrap(middleware::Logger::default())
.default_resource(|r| r.to_async(forward))
.default_service(web::route().to_async(forward))
})
.bind((listen_addr, listen_port))?
.system_exit()

View File

@ -6,12 +6,12 @@ use futures::Poll;
pub struct CheckLogin;
impl<S, P, B> Transform<S> for CheckLogin
impl<S, B> Transform<S> for CheckLogin
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
S::Future: 'static,
{
type Request = ServiceRequest<P>;
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = S::Error;
type InitError = ();
@ -26,12 +26,12 @@ pub struct CheckLoginMiddleware<S> {
service: S,
}
impl<S, P, B> Service for CheckLoginMiddleware<S>
impl<S, B> Service for CheckLoginMiddleware<S>
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
S::Future: 'static,
{
type Request = ServiceRequest<P>;
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = S::Error;
type Future = Either<S::Future, FutureResult<Self::Response, Self::Error>>;
@ -40,7 +40,7 @@ where
self.service.poll_ready()
}
fn call(&mut self, req: ServiceRequest<P>) -> Self::Future {
fn call(&mut self, req: ServiceRequest) -> Self::Future {
// We only need to hook into the `start` for this middleware.
let is_logged_in = false; // Change this to see the change in outcome in the browser

View File

@ -11,16 +11,15 @@ pub struct SayHi;
// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `P` - type of request's payload
// `B` - type of response's body
impl<S, P, B> Transform<S> for SayHi
impl<S, B> Transform<S> for SayHi
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
S::Future: 'static,
S::Error: 'static,
B: 'static,
{
type Request = ServiceRequest<P>;
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = S::Error;
type InitError = ();
@ -36,14 +35,14 @@ pub struct SayHiMiddleware<S> {
service: S,
}
impl<S, P, B> Service for SayHiMiddleware<S>
impl<S, B> Service for SayHiMiddleware<S>
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
S::Future: 'static,
S::Error: 'static,
B: 'static,
{
type Request = ServiceRequest<P>;
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = S::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
@ -52,7 +51,7 @@ where
self.service.poll_ready()
}
fn call(&mut self, req: ServiceRequest<P>) -> Self::Future {
fn call(&mut self, req: ServiceRequest) -> Self::Future {
println!("Hi from start. You requested: {}", req.path());
Box::new(self.service.call(req).and_then(|res| {

View File

@ -1,8 +1,8 @@
use std::cell::Cell;
use std::fs::{self};
use std::fs;
use std::io::Write;
use actix_multipart::{Field, Item, Multipart, MultipartError};
use actix_multipart::{Field, Multipart, MultipartError};
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
use futures::future::{err, Either};
use futures::{Future, Stream};
@ -15,7 +15,7 @@ pub fn save_file(field: Field) -> impl Future<Item = i64, Error = Error> {
let file_path_string = "upload.png";
let mut file = match fs::File::create(file_path_string) {
Ok(file) => file,
Err(e) => return Either::A(err(error::ErrorInternalServerError(e)))
Err(e) => return Either::A(err(error::ErrorInternalServerError(e))),
};
Either::B(
field
@ -34,17 +34,6 @@ pub fn save_file(field: Field) -> impl Future<Item = i64, Error = Error> {
)
}
pub fn handle_multipart_item(item: Item) -> Box<Stream<Item = i64, Error = Error>> {
match item {
Item::Field(field) => Box::new(save_file(field).into_stream()),
Item::Nested(mp) => Box::new(
mp.map_err(error::ErrorInternalServerError)
.map(handle_multipart_item)
.flatten(),
),
}
}
pub fn upload(
multipart: Multipart,
counter: web::Data<Cell<usize>>,
@ -54,7 +43,7 @@ pub fn upload(
multipart
.map_err(error::ErrorInternalServerError)
.map(handle_multipart_item)
.map(|field| save_file(field).into_stream())
.flatten()
.collect()
.map(|sizes| HttpResponse::Ok().json(sizes))

View File

@ -46,11 +46,12 @@ impl Handler<AuthData> for DbExecutor {
// simple aliasing makes the intentions clear and its more readable
pub type LoggedUser = SlimUser;
impl<P> FromRequest<P> for LoggedUser {
impl FromRequest for LoggedUser {
type Config = ();
type Error = Error;
type Future = Result<LoggedUser, Error>;
fn from_request(req: &HttpRequest, pl: &mut Payload<P>) -> Self::Future {
fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
if let Some(identity) = Identity::from_request(req, pl)?.identity() {
let user: SlimUser = decode_token(&identity)?;
return Ok(user as LoggedUser);