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

cleanup and cargo fmt

This commit is contained in:
Nikolay Kim 2018-05-20 21:03:29 -07:00
parent 2d97219195
commit e4f1833215
28 changed files with 108 additions and 112 deletions

10
Cargo.lock generated
View File

@ -1687,6 +1687,16 @@ dependencies = [
"futures 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "static_index"
version = "0.1.0"
dependencies = [
"actix 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"actix-web 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
"futures 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "string"
version = "0.1.0"

View File

@ -15,6 +15,7 @@ members = [
"r2d2",
"redis-session",
"state",
"static_index",
"template_askama",
"template_tera",
"tls",

View File

@ -12,9 +12,8 @@
// - POSTing json body
// 3. chaining futures into a single response used by an asynch endpoint
//
// There are 2 versions in this example, one that uses Boxed Futures and the other that uses Impl
// Future, available since rustc v1.26.
// There are 2 versions in this example, one that uses Boxed Futures and the
// other that uses Impl Future, available since rustc v1.26.
extern crate actix;
extern crate actix_web;
@ -28,12 +27,14 @@ extern crate env_logger;
extern crate futures;
extern crate validator;
use actix_web::{client, dev::Handler, http::Method, server, App, AsyncResponder, Body,
Error, HttpMessage, HttpRequest, HttpResponse, Json, Result};
use actix_web::{
client, http::Method, server, App, AsyncResponder, Error, HttpMessage, HttpResponse,
Json,
};
use futures::{future::ok as fut_ok, Future};
use std::collections::HashMap;
use std::time::Duration;
use validator::{Validate, ValidationError};
use validator::Validate;
#[derive(Debug, Validate, Deserialize, Serialize)]
struct SomeData {
@ -55,7 +56,6 @@ struct HttpBinResponse {
url: String,
}
// -----------------------------------------------------------------------
// v1 uses Boxed Futures, which were the only option prior to rustc v1.26
// -----------------------------------------------------------------------
@ -96,7 +96,6 @@ fn create_something_v1(
.responder()
}
// ---------------------------------------------------------------
// v2 uses impl Future, available as of rustc v1.26
// ---------------------------------------------------------------
@ -118,23 +117,21 @@ fn step_x_v2(data: SomeData) -> impl Future<Item = SomeData, Error = Error> {
)
}
fn create_something_v2(some_data: Json<SomeData>)
-> impl Future<Item = HttpResponse, Error = Error> {
step_x_v2(some_data.into_inner())
.and_then(|some_data_2| {
fn create_something_v2(
some_data: Json<SomeData>,
) -> impl Future<Item = HttpResponse, Error = Error> {
step_x_v2(some_data.into_inner()).and_then(|some_data_2| {
step_x_v2(some_data_2).and_then(|some_data_3| {
step_x_v2(some_data_3).and_then(|d|
step_x_v2(some_data_3).and_then(|d| {
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&d).unwrap())
.into()))
.into())
})
})
})
}
fn main() {
env_logger::init();
let sys = actix::System::new("asyncio_example");
@ -142,11 +139,12 @@ fn main() {
server::new(move || {
App::new()
.resource("/something_v1", |r| {
r.method(Method::POST).with(create_something_v1)})
.resource("/something_v2", |r| {
r.method(Method::POST).with_async(create_something_v2)})
r.method(Method::POST).with(create_something_v1)
})
.bind("127.0.0.1:8088")
.resource("/something_v2", |r| {
r.method(Method::POST).with_async(create_something_v2)
})
}).bind("127.0.0.1:8088")
.unwrap()
.start();

View File

@ -9,8 +9,9 @@ use futures::Stream;
use actix_web::http::{header, Method, StatusCode};
use actix_web::middleware::session::{self, RequestSession};
use actix_web::{error, fs, middleware, pred, server, App, Error, HttpRequest,
HttpResponse, Result};
use actix_web::{
error, fs, middleware, pred, server, App, Error, HttpRequest, HttpResponse, Result,
};
use futures::future::{result, FutureResult};
use std::{env, io};
@ -66,10 +67,7 @@ fn with_param(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.content_type("test/plain")
.body(format!(
"Hello {}!",
req.match_info().get("name").unwrap()
))
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))
}
fn main() {

View File

@ -1,3 +1,4 @@
#![allow(dead_code)]
use std::rc::Rc;
use cookie::{Cookie, CookieJar, Key};
@ -88,7 +89,8 @@ impl<S: 'static, T: IdentityPolicy<S>> Middleware<S> for IdentityService<T> {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
let mut req = req.clone();
let fut = self.backend
let fut = self
.backend
.from_request(&mut req)
.then(move |res| match res {
Ok(id) => {

View File

@ -5,7 +5,6 @@ extern crate env_logger;
extern crate futures;
extern crate time;
use actix_web::middleware::session::RequestSession;
use actix_web::{middleware, server, App, HttpRequest, HttpResponse};
mod auth;

View File

@ -18,8 +18,10 @@ extern crate r2d2;
extern crate uuid;
use actix::prelude::*;
use actix_web::{http, middleware, server, App, AsyncResponder, FutureResponse,
HttpResponse, Path, State};
use actix_web::{
http, middleware, server, App, AsyncResponder, FutureResponse, HttpResponse, Path,
State,
};
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};

View File

@ -3,8 +3,10 @@ extern crate actix_web;
extern crate env_logger;
extern crate futures;
use actix_web::{client, middleware, server, App, AsyncResponder, Body, Error,
HttpMessage, HttpRequest, HttpResponse};
use actix_web::{
client, middleware, server, App, AsyncResponder, Body, Error, HttpMessage,
HttpRequest, HttpResponse,
};
use futures::{Future, Stream};
/// Stream client request response and then send body to a server response

View File

@ -9,8 +9,10 @@ extern crate serde_derive;
#[macro_use]
extern crate json;
use actix_web::{error, http, middleware, server, App, AsyncResponder, Error,
HttpMessage, HttpRequest, HttpResponse, Json};
use actix_web::{
error, http, middleware, server, App, AsyncResponder, Error, HttpMessage,
HttpRequest, HttpResponse, Json,
};
use bytes::BytesMut;
use futures::{Future, Stream};

View File

@ -13,8 +13,10 @@ extern crate env_logger;
extern crate futures;
use actix::prelude::*;
use actix_web::{http, middleware, server, App, AsyncResponder, Error, FutureResponse,
HttpRequest, HttpResponse, Json, State};
use actix_web::{
http, middleware, server, App, AsyncResponder, Error, FutureResponse, HttpRequest,
HttpResponse, Json, State,
};
use futures::future::Future;
use juniper::http::graphiql::graphiql_source;
use juniper::http::GraphQLRequest;

View File

@ -5,8 +5,10 @@ extern crate env_logger;
extern crate futures;
use actix::*;
use actix_web::{http, middleware, multipart, server, App, AsyncResponder, Error,
HttpMessage, HttpRequest, HttpResponse};
use actix_web::{
http, middleware, multipart, server, App, AsyncResponder, Error, HttpMessage,
HttpRequest, HttpResponse,
};
use futures::future::{result, Either};
use futures::{Future, Stream};

View File

@ -9,8 +9,9 @@ extern crate prost;
#[macro_use]
extern crate prost_derive;
use actix_web::{http, middleware, server, App, AsyncResponder, Error, HttpRequest,
HttpResponse};
use actix_web::{
http, middleware, server, App, AsyncResponder, Error, HttpRequest, HttpResponse,
};
use futures::Future;
mod protobuf;

View File

@ -132,7 +132,8 @@ where
}
let limit = self.limit;
let fut = req.from_err()
let fut = req
.from_err()
.fold(BytesMut::new(), move |mut body, chunk| {
if (body.len() + chunk.len()) > limit {
Err(ProtoBufPayloadError::Overflow)

View File

@ -35,10 +35,10 @@ impl Handler<CreateUser> for DbExecutor {
&[&uuid, &msg.name],
).unwrap();
Ok(conn.query_row(
"SELECT name FROM users WHERE id=$1",
&[&uuid],
|row| row.get(0),
).map_err(|_| io::Error::new(io::ErrorKind::Other, "db error"))?)
Ok(conn
.query_row("SELECT name FROM users WHERE id=$1", &[&uuid], |row| {
row.get(0)
})
.map_err(|_| io::Error::new(io::ErrorKind::Other, "db error"))?)
}
}

View File

@ -11,8 +11,9 @@ extern crate serde_json;
extern crate uuid;
use actix::prelude::*;
use actix_web::{http, middleware, server, App, AsyncResponder, Error, HttpRequest,
HttpResponse};
use actix_web::{
http, middleware, server, App, AsyncResponder, Error, HttpRequest, HttpResponse,
};
use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager;

View File

@ -29,10 +29,7 @@ fn index(req: HttpRequest<AppState>) -> HttpResponse {
println!("{:?}", req);
req.state().counter.set(req.state().counter.get() + 1);
HttpResponse::Ok().body(format!(
"Num of requests: {}",
req.state().counter.get()
))
HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.get()))
}
fn main() {

View File

@ -2,14 +2,10 @@
name = "static_index"
version = "0.1.0"
authors = ["Jose Marinez <digeratus@gmail.com>"]
workspace = "../"
[dependencies]
futures = "0.1"
env_logger = "0.5"
actix = "^0.5.5"
actix-web = { git="https://github.com/actix/actix-web.git" }
[workspace]
members = [
"./"
]
actix = "0.5"
actix-web = "0.6"

View File

@ -2,7 +2,7 @@ extern crate actix;
extern crate actix_web;
extern crate env_logger;
use actix_web::{fs, App, server, middleware};
use actix_web::{fs, middleware, server, App};
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
@ -11,22 +11,18 @@ fn main() {
let sys = actix::System::new("static_index");
server::new(
|| App::new()
server::new(|| {
App::new()
// enable logger
.middleware(middleware::Logger::default())
.handler(
"/",
fs::StaticFiles::new("./static/").index_file("index.html")
)
)
.bind("127.0.0.1:8080").expect( "Can not start server on given IP/Port" )
}).bind("127.0.0.1:8080")
.expect("Can not start server on given IP/Port")
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}

View File

@ -6,7 +6,9 @@ extern crate tera;
use std::collections::HashMap;
use actix_web::{error, http, middleware, server, App, Error, HttpResponse, Query, State};
use actix_web::{
error, http, middleware, server, App, Error, HttpResponse, Query, State,
};
struct AppState {
template: tera::Tera, // <- store tera template in application state

View File

@ -27,9 +27,7 @@ fn main() {
builder
.set_private_key_file("key.pem", SslFiletype::PEM)
.unwrap();
builder
.set_certificate_chain_file("cert.pem")
.unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
server::new(|| {
App::new()

View File

@ -7,11 +7,9 @@ extern crate futures;
extern crate serde;
extern crate serde_json;
use actix_web::{http::{header, Method},
middleware,
middleware::cors::Cors,
server,
App};
use actix_web::{
http::{header, Method}, middleware, middleware::cors::Cors, server, App,
};
use std::env;
mod user;

View File

@ -83,9 +83,7 @@ impl Actor for WsChatSession {
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
// notify chat server
ctx.state()
.addr
.do_send(server::Disconnect { id: self.id });
ctx.state().addr.do_send(server::Disconnect { id: self.id });
Running::Stop
}
}

View File

@ -114,10 +114,7 @@ impl Handler<Connect> for ChatServer {
self.sessions.insert(id, msg.addr);
// auto join session to Main room
self.rooms
.get_mut(&"Main".to_owned())
.unwrap()
.insert(id);
self.rooms.get_mut(&"Main".to_owned()).unwrap().insert(id);
// send id back
id

View File

@ -121,8 +121,7 @@ impl Handler<ClientCommand> for ChatClient {
}
"/join" => {
if v.len() == 2 {
self.framed
.write(codec::ChatRequest::Join(v[1].to_owned()));
self.framed.write(codec::ChatRequest::Join(v[1].to_owned()));
} else {
println!("!!! room name is required");
}
@ -130,8 +129,7 @@ impl Handler<ClientCommand> for ChatClient {
_ => println!("!!! unknown command"),
}
} else {
self.framed
.write(codec::ChatRequest::Message(m.to_owned()));
self.framed.write(codec::ChatRequest::Message(m.to_owned()));
}
}
}

View File

@ -71,7 +71,7 @@ impl Encoder for ChatCodec {
let msg_ref: &[u8] = msg.as_ref();
dst.reserve(msg_ref.len() + 2);
dst.put_u16::<BigEndian>(msg_ref.len() as u16);
dst.put_u16_be(msg_ref.len() as u16);
dst.put(msg_ref);
Ok(())
@ -114,7 +114,7 @@ impl Encoder for ClientChatCodec {
let msg_ref: &[u8] = msg.as_ref();
dst.reserve(msg_ref.len() + 2);
dst.put_u16::<BigEndian>(msg_ref.len() as u16);
dst.put_u16_be(msg_ref.len() as u16);
dst.put(msg_ref);
Ok(())

View File

@ -19,7 +19,6 @@ use std::time::Instant;
use actix::*;
use actix_web::server::HttpServer;
use actix_web::ws::WsWriter;
use actix_web::{fs, http, ws, App, Error, HttpRequest, HttpResponse};
mod codec;
@ -88,9 +87,7 @@ impl Actor for WsChatSession {
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
// notify chat server
ctx.state()
.addr
.do_send(server::Disconnect { id: self.id });
ctx.state().addr.do_send(server::Disconnect { id: self.id });
Running::Stop
}
}

View File

@ -112,10 +112,7 @@ impl Handler<Connect> for ChatServer {
self.sessions.insert(id, msg.addr);
// auto join session to Main room
self.rooms
.get_mut(&"Main".to_owned())
.unwrap()
.insert(id);
self.rooms.get_mut(&"Main".to_owned()).unwrap().insert(id);
// send id back
id

View File

@ -9,8 +9,9 @@ extern crate actix_web;
extern crate env_logger;
use actix::prelude::*;
use actix_web::ws::WsWriter;
use actix_web::{fs, http, middleware, server, ws, App, Error, HttpRequest, HttpResponse};
use actix_web::{
fs, http, middleware, server, ws, App, Error, HttpRequest, HttpResponse,
};
/// do websocket handshake and start `MyWebSocket` actor
fn ws_index(r: HttpRequest) -> Result<HttpResponse, Error> {