diff --git a/auth/casbin/src/main.rs b/auth/casbin/src/main.rs index e4166e2..1858f20 100644 --- a/auth/casbin/src/main.rs +++ b/auth/casbin/src/main.rs @@ -5,10 +5,7 @@ use tokio::sync::RwLock; use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer}; /// simple handle -async fn success( - enforcer: web::Data>, - req: HttpRequest, -) -> HttpResponse { +async fn success(enforcer: web::Data>, req: HttpRequest) -> HttpResponse { let mut e = enforcer.write().await; println!("{:?}", req); assert_eq!(vec!["data2_admin"], e.get_roles_for_user("alice", None)); diff --git a/auth/simple-auth-server/src/email_service.rs b/auth/simple-auth-server/src/email_service.rs index 18be45c..bcd1db7 100644 --- a/auth/simple-auth-server/src/email_service.rs +++ b/auth/simple-auth-server/src/email_service.rs @@ -11,8 +11,8 @@ static ref API_KEY: String = std::env::var("SPARKPOST_API_KEY").expect("SPARKPOS pub fn send_invitation(invitation: &Invitation) -> Result<(), ServiceError> { let tm = Transmission::new_eu(API_KEY.as_str()); - let sending_email = std::env::var("SENDING_EMAIL_ADDRESS") - .expect("SENDING_EMAIL_ADDRESS must be set"); + let sending_email = + std::env::var("SENDING_EMAIL_ADDRESS").expect("SENDING_EMAIL_ADDRESS must be set"); // new email message with sender name and email let mut email = Message::new(EmailAddress::new(sending_email, "Let's Organise")); diff --git a/auth/simple-auth-server/src/errors.rs b/auth/simple-auth-server/src/errors.rs index fc64f60..9b7019d 100644 --- a/auth/simple-auth-server/src/errors.rs +++ b/auth/simple-auth-server/src/errors.rs @@ -20,14 +20,11 @@ pub enum ServiceError { impl ResponseError for ServiceError { fn error_response(&self) -> HttpResponse { match self { - ServiceError::InternalServerError => HttpResponse::InternalServerError() - .json("Internal Server Error, Please try later"), - ServiceError::BadRequest(ref message) => { - HttpResponse::BadRequest().json(message) - } - ServiceError::Unauthorized => { - HttpResponse::Unauthorized().json("Unauthorized") + ServiceError::InternalServerError => { + HttpResponse::InternalServerError().json("Internal Server Error, Please try later") } + ServiceError::BadRequest(ref message) => HttpResponse::BadRequest().json(message), + ServiceError::Unauthorized => HttpResponse::Unauthorized().json("Unauthorized"), } } } @@ -47,8 +44,7 @@ impl From for ServiceError { match error { DBError::DatabaseError(kind, info) => { if let DatabaseErrorKind::UniqueViolation = kind { - let message = - info.details().unwrap_or_else(|| info.message()).to_string(); + let message = info.details().unwrap_or_else(|| info.message()).to_string(); return ServiceError::BadRequest(message); } ServiceError::InternalServerError diff --git a/auth/simple-auth-server/src/invitation_handler.rs b/auth/simple-auth-server/src/invitation_handler.rs index 52a4456..ed9c68c 100644 --- a/auth/simple-auth-server/src/invitation_handler.rs +++ b/auth/simple-auth-server/src/invitation_handler.rs @@ -15,8 +15,7 @@ pub async fn post_invitation( pool: web::Data, ) -> Result { // run diesel blocking code - web::block(move || create_invitation(invitation_data.into_inner().email, pool)) - .await??; + web::block(move || create_invitation(invitation_data.into_inner().email, pool)).await??; Ok(HttpResponse::Ok().finish()) } @@ -30,10 +29,7 @@ fn create_invitation( } /// Diesel query -fn query( - eml: String, - pool: web::Data, -) -> Result { +fn query(eml: String, pool: web::Data) -> Result { use crate::schema::invitations::dsl::invitations; let new_invitation: Invitation = eml.into(); diff --git a/auth/simple-auth-server/src/main.rs b/auth/simple-auth-server/src/main.rs index bcdbf37..f137fac 100644 --- a/auth/simple-auth-server/src/main.rs +++ b/auth/simple-auth-server/src/main.rs @@ -31,8 +31,7 @@ async fn main() -> std::io::Result<()> { let pool: models::Pool = r2d2::Pool::builder() .build(manager) .expect("Failed to create pool."); - let domain: String = - std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()); + let domain: String = std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string()); // Start http server HttpServer::new(move || { diff --git a/auth/simple-auth-server/src/utils.rs b/auth/simple-auth-server/src/utils.rs index 848efc3..2f7483a 100644 --- a/auth/simple-auth-server/src/utils.rs +++ b/auth/simple-auth-server/src/utils.rs @@ -20,9 +20,10 @@ pub fn hash_password(password: &str) -> Result { } pub fn verify(hash: &str, password: &str) -> Result { - argon2::verify_encoded_ext(hash, password.as_bytes(), SECRET_KEY.as_bytes(), &[]) - .map_err(|err| { + argon2::verify_encoded_ext(hash, password.as_bytes(), SECRET_KEY.as_bytes(), &[]).map_err( + |err| { dbg!(err); ServiceError::Unauthorized - }) + }, + ) } diff --git a/basics/basics/src/main.rs b/basics/basics/src/main.rs index 6b32566..a8186e8 100644 --- a/basics/basics/src/main.rs +++ b/basics/basics/src/main.rs @@ -9,8 +9,7 @@ use actix_web::{ header::{self, ContentType}, Method, StatusCode, }, - middleware, web, App, Either, HttpRequest, HttpResponse, HttpServer, Responder, - Result, + middleware, web, App, Either, HttpRequest, HttpResponse, HttpServer, Responder, Result, }; use async_stream::stream; @@ -44,8 +43,7 @@ async fn welcome(req: HttpRequest, session: Session) -> Result { async fn default_handler(req_method: Method) -> Result { match req_method { Method::GET => { - let file = NamedFile::open("static/404.html")? - .set_status_code(StatusCode::NOT_FOUND); + let file = NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND); Ok(Either::Left(file)) } _ => Ok(Either::Right(HttpResponse::MethodNotAllowed().finish())), @@ -93,9 +91,7 @@ async fn main() -> io::Result<()> { // with path parameters .service(web::resource("/user/{name}").route(web::get().to(with_param))) // async response body - .service( - web::resource("/async-body/{name}").route(web::get().to(response_body)), - ) + .service(web::resource("/async-body/{name}").route(web::get().to(response_body))) .service( web::resource("/test").to(|req: HttpRequest| match *req.method() { Method::GET => HttpResponse::Ok(), @@ -112,14 +108,14 @@ async fn main() -> io::Result<()> { // static files .service(Files::new("/static", "static").show_files_listing()) // redirect - .service(web::resource("/").route(web::get().to( - |req: HttpRequest| async move { + .service( + web::resource("/").route(web::get().to(|req: HttpRequest| async move { println!("{:?}", req); HttpResponse::Found() .insert_header((header::LOCATION, "static/welcome.html")) .finish() - }, - ))) + })), + ) // default .default_service(web::to(default_handler)) }) diff --git a/basics/error-handling/src/main.rs b/basics/error-handling/src/main.rs index 5ea39f2..68ddcd0 100644 --- a/basics/error-handling/src/main.rs +++ b/basics/error-handling/src/main.rs @@ -93,8 +93,7 @@ async fn main() -> std::io::Result<()> { env_logger::init(); HttpServer::new(move || { - App::new() - .service(web::resource("/something").route(web::get().to(do_something))) + App::new().service(web::resource("/something").route(web::get().to(do_something))) }) .bind("127.0.0.1:8088")? .run() diff --git a/basics/nested-routing/src/handlers/products.rs b/basics/nested-routing/src/handlers/products.rs index 3dd3c94..1e59fb3 100644 --- a/basics/nested-routing/src/handlers/products.rs +++ b/basics/nested-routing/src/handlers/products.rs @@ -2,15 +2,11 @@ use actix_web::{web, Error, HttpResponse}; use crate::common::{Part, Product}; -pub async fn get_products( - _query: web::Query>, -) -> Result { +pub async fn get_products(_query: web::Query>) -> Result { Ok(HttpResponse::Ok().finish()) } -pub async fn add_product( - _new_product: web::Json, -) -> Result { +pub async fn add_product(_new_product: web::Json) -> Result { Ok(HttpResponse::Ok().finish()) } diff --git a/basics/todo/src/api.rs b/basics/todo/src/api.rs index dc66fb7..15f9431 100644 --- a/basics/todo/src/api.rs +++ b/basics/todo/src/api.rs @@ -49,10 +49,7 @@ pub async fn create( session: Session, ) -> Result { if params.description.is_empty() { - session::set_flash( - &session, - FlashMessage::error("Description cannot be empty"), - )?; + session::set_flash(&session, FlashMessage::error("Description cannot be empty"))?; Ok(redirect_to("/")) } else { db::create_task(params.into_inner().description, &pool) @@ -133,9 +130,7 @@ pub fn not_found(res: dev::ServiceResponse) -> Result( - res: dev::ServiceResponse, -) -> Result> { +pub fn internal_server_error(res: dev::ServiceResponse) -> Result> { let new_resp = NamedFile::open("static/errors/500.html")? .set_status_code(res.status()) .into_response(res.request()) diff --git a/basics/todo/src/main.rs b/basics/todo/src/main.rs index a5b6348..52a463e 100644 --- a/basics/todo/src/main.rs +++ b/basics/todo/src/main.rs @@ -32,8 +32,7 @@ async fn main() -> io::Result<()> { HttpServer::new(move || { log::debug!("Constructing the App"); - let mut templates = - Tera::new("templates/**/*").expect("errors in tera templates"); + let mut templates = Tera::new("templates/**/*").expect("errors in tera templates"); templates.autoescape_on(vec!["tera"]); let session_store = CookieSession::signed(SESSION_SIGNING_KEY).secure(false); diff --git a/basics/todo/src/model.rs b/basics/todo/src/model.rs index b9fa582..4166233 100644 --- a/basics/todo/src/model.rs +++ b/basics/todo/src/model.rs @@ -28,10 +28,7 @@ impl Task { Ok(tasks) } - pub async fn insert( - todo: NewTask, - connection: &SqlitePool, - ) -> Result<(), sqlx::Error> { + pub async fn insert(todo: NewTask, connection: &SqlitePool) -> Result<(), sqlx::Error> { sqlx::query!( r#" INSERT INTO tasks (description) @@ -45,10 +42,7 @@ impl Task { Ok(()) } - pub async fn toggle_with_id( - id: i32, - connection: &SqlitePool, - ) -> Result<(), sqlx::Error> { + pub async fn toggle_with_id(id: i32, connection: &SqlitePool) -> Result<(), sqlx::Error> { sqlx::query!( r#" UPDATE tasks @@ -63,10 +57,7 @@ impl Task { Ok(()) } - pub async fn delete_with_id( - id: i32, - connection: &SqlitePool, - ) -> Result<(), sqlx::Error> { + pub async fn delete_with_id(id: i32, connection: &SqlitePool) -> Result<(), sqlx::Error> { sqlx::query!( r#" DELETE FROM tasks diff --git a/databases/diesel/src/main.rs b/databases/diesel/src/main.rs index 0211a8e..39655ab 100644 --- a/databases/diesel/src/main.rs +++ b/databases/diesel/src/main.rs @@ -36,8 +36,7 @@ async fn get_user( if let Some(user) = user { Ok(HttpResponse::Ok().json(user)) } else { - let res = HttpResponse::NotFound() - .body(format!("No user found with uid: {}", user_uid)); + let res = HttpResponse::NotFound().body(format!("No user found with uid: {}", user_uid)); Ok(res) } } diff --git a/databases/mongodb/src/main.rs b/databases/mongodb/src/main.rs index 1aabb73..8dc22c5 100644 --- a/databases/mongodb/src/main.rs +++ b/databases/mongodb/src/main.rs @@ -25,10 +25,7 @@ async fn add_user(client: web::Data, form: web::Form) -> HttpRespo /// Gets the user with the supplied username. #[get("/get_user/{username}")] -async fn get_user( - client: web::Data, - username: web::Path, -) -> HttpResponse { +async fn get_user(client: web::Data, username: web::Path) -> HttpResponse { let username = username.into_inner(); let collection: Collection = client.database(DB_NAME).collection(COLL_NAME); match collection @@ -36,8 +33,9 @@ async fn get_user( .await { Ok(Some(user)) => HttpResponse::Ok().json(user), - Ok(None) => HttpResponse::NotFound() - .body(format!("No user found with username {}", username)), + Ok(None) => { + HttpResponse::NotFound().body(format!("No user found with username {}", username)) + } Err(err) => HttpResponse::InternalServerError().body(err.to_string()), } } @@ -59,8 +57,7 @@ async fn create_username_index(client: &Client) { #[actix_web::main] async fn main() -> std::io::Result<()> { - let uri = std::env::var("MONGODB_URI") - .unwrap_or_else(|_| "mongodb://localhost:27017".into()); + let uri = std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".into()); let client = Client::with_uri_str(uri).await.expect("failed to connect"); create_username_index(&client).await; diff --git a/databases/mongodb/src/test.rs b/databases/mongodb/src/test.rs index 9215a59..3a0b1c7 100644 --- a/databases/mongodb/src/test.rs +++ b/databases/mongodb/src/test.rs @@ -9,8 +9,7 @@ use super::*; #[actix_web::test] #[ignore = "requires MongoDB instance running"] async fn test() { - let uri = std::env::var("MONGODB_URI") - .unwrap_or_else(|_| "mongodb://localhost:27017".into()); + let uri = std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".into()); let client = Client::with_uri_str(uri).await.expect("failed to connect"); diff --git a/databases/redis/src/main.rs b/databases/redis/src/main.rs index 008f545..0f95ad2 100644 --- a/databases/redis/src/main.rs +++ b/databases/redis/src/main.rs @@ -46,9 +46,7 @@ async fn cache_stuff( } } -async fn del_stuff( - redis: web::Data>, -) -> actix_web::Result { +async fn del_stuff(redis: web::Data>) -> actix_web::Result { let res = redis .send(Command(resp_array![ "DEL", diff --git a/databases/sqlite/src/main.rs b/databases/sqlite/src/main.rs index 906692f..4b7641b 100644 --- a/databases/sqlite/src/main.rs +++ b/databases/sqlite/src/main.rs @@ -63,13 +63,8 @@ async fn main() -> io::Result<()> { // store db pool as Data object .app_data(web::Data::new(pool.clone())) .wrap(middleware::Logger::default()) - .service( - web::resource("/asyncio_weather").route(web::get().to(asyncio_weather)), - ) - .service( - web::resource("/parallel_weather") - .route(web::get().to(parallel_weather)), - ) + .service(web::resource("/asyncio_weather").route(web::get().to(asyncio_weather))) + .service(web::resource("/parallel_weather").route(web::get().to(parallel_weather))) }) .bind(("127.0.0.1", 8080))? .workers(2) diff --git a/forms/form/src/main.rs b/forms/form/src/main.rs index 6f7f1d1..547c09b 100644 --- a/forms/form/src/main.rs +++ b/forms/form/src/main.rs @@ -1,8 +1,6 @@ use serde::{Deserialize, Serialize}; -use actix_web::{ - middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result, -}; +use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result}; struct AppState { foo: String, diff --git a/forms/multipart-s3/src/main.rs b/forms/multipart-s3/src/main.rs index ff3edab..be6982b 100644 --- a/forms/multipart-s3/src/main.rs +++ b/forms/multipart-s3/src/main.rs @@ -23,8 +23,7 @@ async fn save_file(mut payload: Multipart) -> Result { //make key let s3_upload_key = format!("projects/{}/", "posts_id"); //create tmp file and upload s3 and remove tmp file - let upload_files: Vec = - upload_save_file(pl.1, s3_upload_key).await.unwrap(); + let upload_files: Vec = upload_save_file(pl.1, s3_upload_key).await.unwrap(); println!("upload_files={:#?}", upload_files); Ok(HttpResponse::Ok().into()) } @@ -79,8 +78,7 @@ async fn main() -> std::io::Result<()> { dotenv().ok(); env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - let aws_access_key_id = - env::var("AWS_ACCESS_KEY_ID").expect("AWS_ACCESS_KEY_ID must be set"); + let aws_access_key_id = env::var("AWS_ACCESS_KEY_ID").expect("AWS_ACCESS_KEY_ID must be set"); let aws_secret_access_key = env::var("AWS_SECRET_ACCESS_KEY").expect("AWS_SECRET_ACCESS_KEY must be set"); let aws_s3_bucket_name = diff --git a/graphql/async-graphql/src/main.rs b/graphql/async-graphql/src/main.rs index fe2a04d..c23752e 100644 --- a/graphql/async-graphql/src/main.rs +++ b/graphql/async-graphql/src/main.rs @@ -12,10 +12,7 @@ use self::star_wars::{QueryRoot, StarWars, StarWarsSchema}; /// GraphQL endpoint #[route("/graphql", method = "GET", method = "POST")] -async fn graphql( - schema: web::Data, - req: GraphQLRequest, -) -> GraphQLResponse { +async fn graphql(schema: web::Data, req: GraphQLRequest) -> GraphQLResponse { schema.execute(req.into_inner()).await.into() } diff --git a/graphql/juniper/src/main.rs b/graphql/juniper/src/main.rs index 3001903..40d6f8b 100644 --- a/graphql/juniper/src/main.rs +++ b/graphql/juniper/src/main.rs @@ -25,10 +25,7 @@ async fn graphql_playground() -> impl Responder { /// GraphQL endpoint #[route("/graphql", method = "GET", method = "POST")] -async fn graphql( - st: web::Data, - data: web::Json, -) -> impl Responder { +async fn graphql(st: web::Data, data: web::Json) -> impl Responder { let user = data.execute(&st, &()).await; HttpResponse::Ok().json(user) } diff --git a/http-proxy/src/main.rs b/http-proxy/src/main.rs index 63d2a63..99edfec 100644 --- a/http-proxy/src/main.rs +++ b/http-proxy/src/main.rs @@ -1,8 +1,6 @@ use std::net::ToSocketAddrs; -use actix_web::{ - error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, -}; +use actix_web::{error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer}; use awc::Client; use clap::StructOpt; use url::Url; @@ -23,9 +21,7 @@ async fn forward( .request_from(new_url.as_str(), req.head()) .no_decompress(); let forwarded_req = match req.head().peer_addr { - Some(addr) => { - forwarded_req.insert_header(("x-forwarded-for", format!("{}", addr.ip()))) - } + Some(addr) => forwarded_req.insert_header(("x-forwarded-for", format!("{}", addr.ip()))), None => forwarded_req, }; @@ -37,9 +33,7 @@ async fn forward( let mut client_resp = HttpResponse::build(res.status()); // Remove `Connection` as per // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection#Directives - for (header_name, header_value) in - res.headers().iter().filter(|(h, _)| *h != "connection") - { + for (header_name, header_value) in res.headers().iter().filter(|(h, _)| *h != "connection") { client_resp.insert_header((header_name.clone(), header_value.clone())); } diff --git a/https-tls/awc-https/src/main.rs b/https-tls/awc-https/src/main.rs index 4d2f851..e40038c 100644 --- a/https-tls/awc-https/src/main.rs +++ b/https-tls/awc-https/src/main.rs @@ -66,15 +66,13 @@ async fn main() -> std::io::Result<()> { /// Create simple rustls client config from root certificates. fn rustls_config() -> ClientConfig { let mut root_store = RootCertStore::empty(); - root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map( - |ta| { - OwnedTrustAnchor::from_subject_spki_name_constraints( - ta.subject, - ta.spki, - ta.name_constraints, - ) - }, - )); + root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| { + OwnedTrustAnchor::from_subject_spki_name_constraints( + ta.subject, + ta.spki, + ta.name_constraints, + ) + })); rustls::ClientConfig::builder() .with_safe_defaults() diff --git a/https-tls/openssl-auto-le/src/main.rs b/https-tls/openssl-auto-le/src/main.rs index 91c7a66..d2161ee 100644 --- a/https-tls/openssl-auto-le/src/main.rs +++ b/https-tls/openssl-auto-le/src/main.rs @@ -10,10 +10,7 @@ use openssl::{ x509::X509, }; -pub async fn gen_tls_cert( - user_email: &str, - user_domain: &str, -) -> anyhow::Result { +pub async fn gen_tls_cert(user_email: &str, user_domain: &str) -> anyhow::Result { // Create acme-challenge dir. fs::create_dir("./acme-challenge").unwrap(); diff --git a/https-tls/rustls-client-cert/src/main.rs b/https-tls/rustls-client-cert/src/main.rs index 778814d..42aab36 100644 --- a/https-tls/rustls-client-cert/src/main.rs +++ b/https-tls/rustls-client-cert/src/main.rs @@ -5,13 +5,11 @@ use std::{any::Any, env, fs::File, io::BufReader, net::SocketAddr}; use actix_tls::accept::rustls::{reexports::ServerConfig, TlsStream}; use actix_web::{ - dev::Extensions, rt::net::TcpStream, web, App, HttpRequest, HttpResponse, - HttpServer, Responder, + dev::Extensions, rt::net::TcpStream, web, App, HttpRequest, HttpResponse, HttpServer, Responder, }; use log::info; use rustls::{ - server::AllowAnyAnonymousOrAuthenticatedClient, Certificate, PrivateKey, - RootCertStore, + server::AllowAnyAnonymousOrAuthenticatedClient, Certificate, PrivateKey, RootCertStore, }; use rustls_pemfile::{certs, pkcs8_private_keys}; diff --git a/json/json-decode-error/src/main.rs b/json/json-decode-error/src/main.rs index 71d0524..8094854 100644 --- a/json/json-decode-error/src/main.rs +++ b/json/json-decode-error/src/main.rs @@ -1,6 +1,4 @@ -use actix_web::{ - error, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder, -}; +use actix_web::{error, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use serde::Deserialize; #[derive(Deserialize)] @@ -18,9 +16,7 @@ fn json_error_handler(err: error::JsonPayloadError, _req: &HttpRequest) -> error let detail = err.to_string(); let resp = match &err { - JsonPayloadError::ContentType => { - HttpResponse::UnsupportedMediaType().body(detail) - } + JsonPayloadError::ContentType => HttpResponse::UnsupportedMediaType().body(detail), JsonPayloadError::Deserialize(json_err) if json_err.is_data() => { HttpResponse::UnprocessableEntity().body(detail) } diff --git a/json/json-error/src/main.rs b/json/json-error/src/main.rs index 0bf3975..c15318c 100644 --- a/json/json-error/src/main.rs +++ b/json/json-error/src/main.rs @@ -23,8 +23,7 @@ impl ResponseError for Error { // builds the actual response to send back when an error occurs fn error_response(&self) -> web::HttpResponse { let err_json = json!({ "error": self.msg }); - web::HttpResponse::build(StatusCode::from_u16(self.status).unwrap()) - .json(err_json) + web::HttpResponse::build(StatusCode::from_u16(self.status).unwrap()).json(err_json) } } @@ -40,11 +39,9 @@ async fn main() -> io::Result<()> { let ip_address = "127.0.0.1:8000"; println!("Running server on {}", ip_address); - HttpServer::new(|| { - App::new().service(web::resource("/").route(web::get().to(index))) - }) - .bind(ip_address) - .expect("Can not bind to port 8000") - .run() - .await + HttpServer::new(|| App::new().service(web::resource("/").route(web::get().to(index)))) + .bind(ip_address) + .expect("Can not bind to port 8000") + .run() + .await } diff --git a/json/json/src/main.rs b/json/json/src/main.rs index f9b1f5a..1311424 100644 --- a/json/json/src/main.rs +++ b/json/json/src/main.rs @@ -1,6 +1,4 @@ -use actix_web::{ - error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, -}; +use actix_web::{error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer}; use futures::StreamExt; use json::JsonValue; use serde::{Deserialize, Serialize}; @@ -92,10 +90,9 @@ mod tests { #[actix_web::test] async fn test_index() { - let app = test::init_service( - App::new().service(web::resource("/").route(web::post().to(index))), - ) - .await; + let app = + test::init_service(App::new().service(web::resource("/").route(web::post().to(index)))) + .await; let req = test::TestRequest::post() .uri("/") diff --git a/json/jsonrpc/src/main.rs b/json/jsonrpc/src/main.rs index 18ea7a4..d288b34 100644 --- a/json/jsonrpc/src/main.rs +++ b/json/jsonrpc/src/main.rs @@ -18,10 +18,7 @@ use serde_json::Value; mod convention; /// The main handler for JSONRPC server. -async fn rpc_handler( - body: Bytes, - app_state: web::Data, -) -> Result { +async fn rpc_handler(body: Bytes, app_state: web::Data) -> Result { let reqjson: convention::Request = match serde_json::from_slice(body.as_ref()) { Ok(ok) => ok, Err(_) => { @@ -90,10 +87,7 @@ async fn rpc_select( pub trait ImplNetwork { fn ping(&self) -> String; - fn wait( - &self, - d: u64, - ) -> Pin>>>>; + fn wait(&self, d: u64) -> Pin>>>>; fn get(&self) -> u32; fn inc(&mut self); @@ -114,10 +108,7 @@ impl ImplNetwork for ObjNetwork { String::from("pong") } - fn wait( - &self, - d: u64, - ) -> Pin>>>> { + fn wait(&self, d: u64) -> Pin>>>> { async move { actix_web::rt::time::sleep(Duration::from_secs(d)).await; Ok(String::from("pong")) diff --git a/middleware/middleware-http-to-https/src/main.rs b/middleware/middleware-http-to-https/src/main.rs index eba165f..1ea570e 100644 --- a/middleware/middleware-http-to-https/src/main.rs +++ b/middleware/middleware-http-to-https/src/main.rs @@ -7,9 +7,7 @@ use rustls_pemfile::{certs, pkcs8_private_keys}; #[get("/")] async fn index() -> String { - String::from( - "FOO BAR

FOO BAR

", - ) + String::from("FOO BAR

FOO BAR

") } #[actix_web::main] diff --git a/middleware/middleware/src/main.rs b/middleware/middleware/src/main.rs index 8f8dd94..66ec56d 100644 --- a/middleware/middleware/src/main.rs +++ b/middleware/middleware/src/main.rs @@ -32,9 +32,11 @@ async fn main() -> std::io::Result<()> { .service(web::resource("/login").to(|| async { "You are on /login. Go to src/redirect.rs to change this behavior." })) - .service(web::resource("/").to(|| async { - "Hello, middleware! Check the console where the server is run." - })) + .service( + web::resource("/").to(|| async { + "Hello, middleware! Check the console where the server is run." + }), + ) }) .bind(("127.0.0.1", 8080))? .run() diff --git a/rustfmt.toml b/rustfmt.toml index 94bd11d..44148a2 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,2 +1 @@ -max_width = 89 reorder_imports = true diff --git a/server-sent-events/src/broadcast.rs b/server-sent-events/src/broadcast.rs index c0e41d5..7136e2f 100644 --- a/server-sent-events/src/broadcast.rs +++ b/server-sent-events/src/broadcast.rs @@ -37,10 +37,8 @@ impl Broadcaster { fn spawn_ping(me: Data>) { actix_web::rt::spawn(async move { - let mut task = IntervalStream::new(interval_at( - Instant::now(), - Duration::from_secs(10), - )); + let mut task = + IntervalStream::new(interval_at(Instant::now(), Duration::from_secs(10))); while task.next().await.is_some() { me.lock().remove_stale_clients(); @@ -85,10 +83,7 @@ pub struct Client(ReceiverStream); impl Stream for Client { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match Pin::new(&mut self.0).poll_next(cx) { Poll::Ready(Some(v)) => Poll::Ready(Some(Ok(v))), Poll::Ready(None) => Poll::Ready(None), diff --git a/server-sent-events/src/main.rs b/server-sent-events/src/main.rs index 04d6821..4e5302d 100644 --- a/server-sent-events/src/main.rs +++ b/server-sent-events/src/main.rs @@ -46,10 +46,7 @@ async fn new_client(broadcaster: Data>) -> impl Responder { .streaming(rx) } -async fn broadcast( - msg: Path, - broadcaster: Data>, -) -> impl Responder { +async fn broadcast(msg: Path, broadcaster: Data>) -> impl Responder { broadcaster.lock().send(&msg.into_inner()); HttpResponse::Ok().body("msg sent") } diff --git a/templating/handlebars/src/main.rs b/templating/handlebars/src/main.rs index 9975b70..2d5dca8 100644 --- a/templating/handlebars/src/main.rs +++ b/templating/handlebars/src/main.rs @@ -20,10 +20,7 @@ async fn index(hb: web::Data>) -> HttpResponse { } #[get("/{user}/{data}")] -async fn user( - hb: web::Data>, - path: web::Path<(String, String)>, -) -> HttpResponse { +async fn user(hb: web::Data>, path: web::Path<(String, String)>) -> HttpResponse { let info = path.into_inner(); let data = json!({ "user": info.0, @@ -72,10 +69,7 @@ fn not_found(res: ServiceResponse) -> Result } // Generic error handler. -fn get_error_response( - res: &ServiceResponse, - error: &str, -) -> HttpResponse { +fn get_error_response(res: &ServiceResponse, error: &str) -> HttpResponse { let request = res.request(); // Provide a fallback to a simple plain text response in case an error occurs during the diff --git a/templating/tera/src/main.rs b/templating/tera/src/main.rs index 5e49583..a96e678 100644 --- a/templating/tera/src/main.rs +++ b/templating/tera/src/main.rs @@ -33,8 +33,7 @@ async fn main() -> std::io::Result<()> { println!("Listening on: 127.0.0.1:8080, open browser and visit have a try!"); HttpServer::new(|| { - let tera = - Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap(); + let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap(); App::new() .app_data(web::Data::new(tera)) diff --git a/templating/yarte/src/main.rs b/templating/yarte/src/main.rs index 2ad1091..79059ce 100644 --- a/templating/yarte/src/main.rs +++ b/templating/yarte/src/main.rs @@ -13,9 +13,7 @@ impl ResponseError for MyErr {} #[allow(unused_must_use)] // ywrite_min causes warning: unused borrow that must be used #[get("/")] -async fn index( - query: web::Query>, -) -> Result { +async fn index(query: web::Query>) -> Result { // `ywrite_min` is work in progress check your templates before put in production // or use `ywrite_html` Ok(HttpResponse::Ok() diff --git a/unix-socket/src/main.rs b/unix-socket/src/main.rs index bbaf4fc..9c6a923 100644 --- a/unix-socket/src/main.rs +++ b/unix-socket/src/main.rs @@ -14,10 +14,7 @@ async fn main() -> std::io::Result<()> { App::new() // enable logger - always register Actix Web Logger middleware last .wrap(middleware::Logger::default()) - .service( - web::resource("/index.html") - .route(web::get().to(|| async { "Hello world!" })), - ) + .service(web::resource("/index.html").route(web::get().to(|| async { "Hello world!" }))) .service(web::resource("/").to(index)) }) .bind_uds("/tmp/actix-uds.socket")? diff --git a/websockets/autobahn/src/main.rs b/websockets/autobahn/src/main.rs index 8919c81..670b497 100644 --- a/websockets/autobahn/src/main.rs +++ b/websockets/autobahn/src/main.rs @@ -14,11 +14,7 @@ impl Actor for AutobahnWebSocket { } impl StreamHandler> for AutobahnWebSocket { - fn handle( - &mut self, - msg: Result, - ctx: &mut Self::Context, - ) { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { if let Ok(msg) = msg { match msg { ws::Message::Text(text) => ctx.text(text), diff --git a/websockets/chat-broker/src/main.rs b/websockets/chat-broker/src/main.rs index 13f9969..8f4a2b5 100644 --- a/websockets/chat-broker/src/main.rs +++ b/websockets/chat-broker/src/main.rs @@ -1,7 +1,5 @@ use actix_files::{Files, NamedFile}; -use actix_web::{ - middleware::Logger, web, App, Error, HttpRequest, HttpServer, Responder, -}; +use actix_web::{middleware::Logger, web, App, Error, HttpRequest, HttpServer, Responder}; use actix_web_actors::ws; mod message; @@ -14,10 +12,7 @@ async fn index() -> impl Responder { NamedFile::open_async("./static/index.html").await.unwrap() } -async fn chat_ws( - req: HttpRequest, - stream: web::Payload, -) -> Result { +async fn chat_ws(req: HttpRequest, stream: web::Payload) -> Result { ws::start(WsChatSession::default(), &req, stream) } diff --git a/websockets/chat-broker/src/server.rs b/websockets/chat-broker/src/server.rs index a2c3327..f27793e 100644 --- a/websockets/chat-broker/src/server.rs +++ b/websockets/chat-broker/src/server.rs @@ -20,12 +20,7 @@ impl WsChatServer { Some(room) } - fn add_client_to_room( - &mut self, - room_name: &str, - id: Option, - client: Client, - ) -> usize { + fn add_client_to_room(&mut self, room_name: &str, id: Option, client: Client) -> usize { let mut id = id.unwrap_or_else(rand::random::); if let Some(room) = self.rooms.get_mut(room_name) { @@ -50,12 +45,7 @@ impl WsChatServer { id } - fn send_chat_message( - &mut self, - room_name: &str, - msg: &str, - _src: usize, - ) -> Option<()> { + fn send_chat_message(&mut self, room_name: &str, msg: &str, _src: usize) -> Option<()> { let mut room = self.take_room(room_name)?; for (id, client) in room.drain() { diff --git a/websockets/chat-broker/src/session.rs b/websockets/chat-broker/src/session.rs index 5a22323..84afc7d 100644 --- a/websockets/chat-broker/src/session.rs +++ b/websockets/chat-broker/src/session.rs @@ -101,11 +101,7 @@ impl Handler for WsChatSession { } impl StreamHandler> for WsChatSession { - fn handle( - &mut self, - msg: Result, - ctx: &mut Self::Context, - ) { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { let msg = match msg { Err(_) => { ctx.stop(); diff --git a/websockets/chat-tcp/src/codec.rs b/websockets/chat-tcp/src/codec.rs index daa369c..e02dc9f 100644 --- a/websockets/chat-tcp/src/codec.rs +++ b/websockets/chat-tcp/src/codec.rs @@ -68,11 +68,7 @@ impl Decoder for ChatCodec { impl Encoder for ChatCodec { type Error = io::Error; - fn encode( - &mut self, - msg: ChatResponse, - dst: &mut BytesMut, - ) -> Result<(), Self::Error> { + fn encode(&mut self, msg: ChatResponse, dst: &mut BytesMut) -> Result<(), Self::Error> { let msg = json::to_string(&msg).unwrap(); let msg_ref: &[u8] = msg.as_ref(); @@ -112,11 +108,7 @@ impl Decoder for ClientChatCodec { impl Encoder for ClientChatCodec { type Error = io::Error; - fn encode( - &mut self, - msg: ChatRequest, - dst: &mut BytesMut, - ) -> Result<(), Self::Error> { + fn encode(&mut self, msg: ChatRequest, dst: &mut BytesMut) -> Result<(), Self::Error> { let msg = json::to_string(&msg).unwrap(); let msg_ref: &[u8] = msg.as_ref(); diff --git a/websockets/chat-tcp/src/main.rs b/websockets/chat-tcp/src/main.rs index 166e35b..6d3f80e 100644 --- a/websockets/chat-tcp/src/main.rs +++ b/websockets/chat-tcp/src/main.rs @@ -2,9 +2,7 @@ use std::time::{Duration, Instant}; use actix::prelude::*; use actix_files::NamedFile; -use actix_web::{ - middleware::Logger, web, App, Error, HttpRequest, HttpServer, Responder, -}; +use actix_web::{middleware::Logger, web, App, Error, HttpRequest, HttpServer, Responder}; use actix_web_actors::ws; mod codec; @@ -103,11 +101,7 @@ impl Handler for WsChatSession { /// WebSocket message handler impl StreamHandler> for WsChatSession { - fn handle( - &mut self, - msg: Result, - ctx: &mut Self::Context, - ) { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { let msg = match msg { Err(_) => { ctx.stop(); diff --git a/websockets/chat/src/main.rs b/websockets/chat/src/main.rs index e7f4b2e..13ddcdb 100644 --- a/websockets/chat/src/main.rs +++ b/websockets/chat/src/main.rs @@ -9,8 +9,7 @@ use std::{ use actix::*; use actix_files::{Files, NamedFile}; use actix_web::{ - middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer, - Responder, + middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder, }; use actix_web_actors::ws; diff --git a/websockets/chat/src/session.rs b/websockets/chat/src/session.rs index a521d03..8594711 100644 --- a/websockets/chat/src/session.rs +++ b/websockets/chat/src/session.rs @@ -105,11 +105,7 @@ impl Handler for WsChatSession { /// WebSocket message handler impl StreamHandler> for WsChatSession { - fn handle( - &mut self, - msg: Result, - ctx: &mut Self::Context, - ) { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { let msg = match msg { Err(_) => { ctx.stop(); diff --git a/websockets/echo/src/main.rs b/websockets/echo/src/main.rs index f6a5153..5a06497 100644 --- a/websockets/echo/src/main.rs +++ b/websockets/echo/src/main.rs @@ -3,9 +3,7 @@ //! Open `http://localhost:8080/` in browser to test. use actix_files::NamedFile; -use actix_web::{ - middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder, -}; +use actix_web::{middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web_actors::ws; mod server; diff --git a/websockets/echo/src/server.rs b/websockets/echo/src/server.rs index 8503196..f1bf818 100644 --- a/websockets/echo/src/server.rs +++ b/websockets/echo/src/server.rs @@ -55,11 +55,7 @@ impl Actor for MyWebSocket { /// Handler for `ws::Message` impl StreamHandler> for MyWebSocket { - fn handle( - &mut self, - msg: Result, - ctx: &mut Self::Context, - ) { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { // process websocket messages println!("WS: {:?}", msg); match msg {