1
0
mirror of https://github.com/actix/examples synced 2024-11-23 14:31:07 +01:00

Use captured args in format string (#558)

This commit is contained in:
Yuri Astrakhan 2022-06-07 22:53:38 -04:00 committed by GitHub
parent 912de4aa46
commit db5f00e771
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 57 additions and 60 deletions

View File

@ -7,7 +7,7 @@ use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
/// simple handle
async fn success(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpResponse {
let mut e = enforcer.write().await;
println!("{:?}", req);
println!("{req:?}");
assert_eq!(vec!["data2_admin"], e.get_roles_for_user("alice", None));
HttpResponse::Ok().body("Success: alice is data2_admin.")
@ -15,7 +15,7 @@ async fn success(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> Htt
async fn fail(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpResponse {
let mut e = enforcer.write().await;
println!("{:?}", req);
println!("{req:?}");
assert_eq!(vec!["data1_admin"], e.get_roles_for_user("alice", None));
HttpResponse::Ok().body("Fail: alice is not data1_admin.") // In fact, it can't be displayed.

View File

@ -10,12 +10,12 @@ use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Result};
/// simple index handler with session
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
log::info!("{:?}", req);
log::info!("{req:?}");
// RequestSession trait is used for session access
let mut counter = 1;
if let Some(count) = session.get::<i32>("counter")? {
log::info!("SESSION value: {}", count);
log::info!("SESSION value: {count}");
counter = count + 1;
session.insert("counter", counter)?;
} else {

View File

@ -65,7 +65,7 @@ async fn logout(session: Session) -> Result<String> {
let id: Option<String> = session.get("user_id")?;
if let Some(x) = id {
session.purge();
Ok(format!("Logged out: {}", x))
Ok(format!("Logged out: {x}"))
} else {
Ok("Could not log out anonymous user".into())
}

View File

@ -22,12 +22,12 @@ async fn favicon() -> Result<impl Responder> {
/// simple index handler
#[get("/welcome")]
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
println!("{:?}", req);
println!("{req:?}");
// session
let mut counter = 1;
if let Some(count) = session.get::<i32>("counter")? {
println!("SESSION value: {}", count);
println!("SESSION value: {count}");
counter = count + 1;
}
@ -63,7 +63,7 @@ async fn response_body(path: web::Path<String>) -> HttpResponse {
/// handler with path parameters like `/user/{name}/`
async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {
println!("{:?}", req);
println!("{req:?}");
HttpResponse::Ok()
.content_type(ContentType::plaintext())
@ -110,7 +110,7 @@ async fn main() -> io::Result<()> {
// redirect
.service(
web::resource("/").route(web::get().to(|req: HttpRequest| async move {
println!("{:?}", req);
println!("{req:?}");
HttpResponse::Found()
.insert_header((header::LOCATION, "static/welcome.html"))
.finish()

View File

@ -1,7 +1,7 @@
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
println!("REQ: {req:?}");
"Hello world!"
}

View File

@ -36,7 +36,7 @@ async fn index(
counter_atomic: Data<AtomicUsize>,
req: HttpRequest,
) -> HttpResponse {
println!("{:?}", req);
println!("{req:?}");
// Increment the counters
*counter_mutex.lock().unwrap() += 1;

View File

@ -80,7 +80,7 @@ pub async fn update(
"put" => toggle(db, params).await,
"delete" => delete(db, params, session).await,
unsupported_method => {
let msg = format!("Unsupported HTTP method: {}", unsupported_method);
let msg = format!("Unsupported HTTP method: {unsupported_method}");
Err(error::ErrorBadRequest(msg))
}
}

View File

@ -11,7 +11,7 @@ pub struct Info {
#[post("/user/info")]
pub async fn info(info: web::Json<Info>) -> web::Json<Info> {
println!("=========={:?}=========", info);
println!("=========={info:?}=========");
web::Json(Info {
username: info.username.clone(),
email: info.email.clone(),

View File

@ -36,7 +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)
}
}

View File

@ -34,7 +34,7 @@ async fn get_user(client: web::Data<Client>, username: web::Path<String>) -> Htt
{
Ok(Some(user)) => HttpResponse::Ok().json(user),
Ok(None) => {
HttpResponse::NotFound().body(format!("No user found with username {}", username))
HttpResponse::NotFound().body(format!("No user found with username {username}"))
}
Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
}

View File

@ -64,7 +64,7 @@ async fn del_stuff(redis: web::Data<Addr<RedisActor>>) -> actix_web::Result<Http
}
_ => {
log::error!("{:?}", res);
log::error!("{res:?}");
Ok(HttpResponse::InternalServerError().finish())
}
}

View File

@ -62,7 +62,7 @@ async fn handle_post_2(
/// Request and POST Params
async fn handle_post_3(req: HttpRequest, params: web::Form<MyParams>) -> impl Responder {
println!("Handling POST request: {:?}", req);
println!("Handling POST request: {req:?}");
HttpResponse::Ok()
.content_type("text/plain")

View File

@ -81,9 +81,9 @@ async fn main() -> std::io::Result<()> {
let aws_s3_bucket_name =
env::var("AWS_S3_BUCKET_NAME").expect("AWS_S3_BUCKET_NAME must be set");
log::info!("aws_access_key_id: {}", aws_access_key_id);
log::info!("aws_secret_access_key: {}", aws_secret_access_key);
log::info!("aws_s3_bucket_name: {}", aws_s3_bucket_name);
log::info!("aws_access_key_id: {aws_access_key_id}");
log::info!("aws_secret_access_key: {aws_secret_access_key}");
log::info!("aws_s3_bucket_name: {aws_s3_bucket_name}");
std::fs::create_dir_all("./tmp").unwrap();

View File

@ -24,10 +24,9 @@ impl Client {
pub fn url(&self, key: &str) -> String {
format!(
"https://{}.s3.{}.amazonaws.com/{}",
"https://{}.s3.{}.amazonaws.com/{key}",
std::env::var("AWS_S3_BUCKET_NAME").unwrap(),
std::env::var("AWS_REGION").unwrap(),
key
)
}

View File

@ -39,7 +39,7 @@ impl Tmpfile {
fn new(filename: &str) -> Tmpfile {
Tmpfile {
name: filename.to_string(),
tmp_path: format!("./tmp/{}", filename),
tmp_path: format!("./tmp/{filename}"),
s3_key: "".to_string(),
s3_url: "".to_string(),
}
@ -51,7 +51,7 @@ impl Tmpfile {
}
async fn s3_upload(&mut self, s3_upload_key: String) {
let key = format!("{}{}", &s3_upload_key, &self.name);
let key = format!("{s3_upload_key}{}", &self.name);
self.s3_key = key.clone();
let url: String = Client::new().put_object(&self.tmp_path, &key.clone()).await;
self.s3_url = url;

View File

@ -14,7 +14,7 @@ async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
let filename = content_disposition
.get_filename()
.map_or_else(|| Uuid::new_v4().to_string(), sanitize_filename::sanitize);
let filepath = format!("./tmp/{}", filename);
let filepath = format!("./tmp/{filename}");
// File::create is blocking operation, use threadpool
let mut f = web::block(|| std::fs::File::create(filepath)).await??;

View File

@ -59,7 +59,7 @@ async fn main() -> std::io::Result<()> {
.next()
.expect("given forwarding address was not valid");
let forward_url = format!("http://{}", forward_socket_addr);
let forward_url = format!("http://{forward_socket_addr}");
let forward_url = Url::parse(&forward_url).unwrap();
log::info!(

View File

@ -90,7 +90,7 @@ pub async fn gen_tls_cert(user_email: &str, user_domain: &str) -> anyhow::Result
let proof = chall.http_proof()?;
// Place the file/contents in the correct place.
let path = format!("acme-challenge/{}", token);
let path = format!("acme-challenge/{token}");
fs::write(&path, &proof)?;
// After the file is accessible from the web, the calls

View File

@ -5,7 +5,7 @@ use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
/// simple handle
async fn index(req: HttpRequest) -> Result<HttpResponse, Error> {
println!("{:?}", req);
println!("{req:?}");
Ok(HttpResponse::Ok()
.content_type("text/plain")
.body("Welcome!"))

View File

@ -11,7 +11,7 @@ use rustls_pemfile::{certs, pkcs8_private_keys};
/// simple handle
async fn index(req: HttpRequest) -> HttpResponse {
debug!("{:?}", req);
debug!("{req:?}");
HttpResponse::Ok().content_type(ContentType::html()).body(
"<!DOCTYPE html><html><body>\

View File

@ -59,7 +59,7 @@ async fn step_x(data: SomeData, client: &Client) -> actix_web::Result<SomeData>
let body: HttpBinResponse = serde_json::from_slice(&body).unwrap();
println!("{:?}", body);
println!("{body:?}");
Ok(body.json)
}

View File

@ -17,8 +17,8 @@ async fn index(item: web::Json<MyObj>) -> HttpResponse {
/// This handler uses json extractor with limit
async fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
println!("request: {:?}", req);
println!("model: {:?}", item);
println!("request: {req:?}");
println!("model: {item:?}");
HttpResponse::Ok().json(item.0) // <- send json response
}

View File

@ -70,7 +70,7 @@ async fn rpc_select(
.await
{
Ok(ok) => Ok(Value::from(ok)),
Err(e) => Err(convention::ErrorData::new(500, &format!("{:?}", e)[..])),
Err(e) => Err(convention::ErrorData::new(500, &format!("{e:?}")[..])),
}
}
"get" => {

View File

@ -41,7 +41,7 @@ async fn main() -> std::io::Result<()> {
.wrap_fn(|sreq, srv| {
let host = sreq.connection_info().host().to_owned();
let uri = sreq.uri().to_owned();
let url = format!("https://{}{}", host, uri);
let url = format!("https://{host}{uri}");
// If the scheme is "https" then it will let other services below this wrap_fn
// handle the request and if it's "http" then a response with redirect status code

View File

@ -58,7 +58,7 @@ where
body.extend_from_slice(&chunk?);
}
println!("request body: {:?}", body);
println!("request body: {body:?}");
let res = svc.call(req).await?;
println!("response: {:?}", res.headers());

View File

@ -12,7 +12,7 @@ pub struct MyObj {
}
async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
log::info!("model: {:?}", msg);
log::info!("model: {msg:?}");
HttpResponse::Ok().protobuf(msg.0) // <- send response
}

View File

@ -7,7 +7,7 @@ use std::{sync::mpsc, thread, time};
use actix_web::{dev::ServerHandle, middleware, rt, web, App, HttpRequest, HttpServer};
async fn index(req: HttpRequest) -> &'static str {
log::info!("REQ: {:?}", req);
log::info!("REQ: {req:?}");
"Hello world!"
}

View File

@ -75,9 +75,8 @@ impl Handler<JoinRoom> for WsChatServer {
let id = self.add_client_to_room(&room_name, None, client);
let join_msg = format!(
"{} joined {}",
"{} joined {room_name}",
client_name.unwrap_or_else(|| "anon".to_string()),
room_name
);
self.send_chat_message(&room_name, &join_msg, id);

View File

@ -63,9 +63,8 @@ impl WsChatSession {
pub fn send_msg(&self, msg: &str) {
let content = format!(
"{}: {}",
"{}: {msg}",
self.name.clone().unwrap_or_else(|| "anon".to_string()),
msg
);
let msg = SendMessage(self.room.clone(), self.id, content);
@ -110,7 +109,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
Ok(msg) => msg,
};
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
match msg {
ws::Message::Text(text) => {
@ -133,13 +132,13 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
Some("/name") => {
if let Some(name) = command.next() {
self.name = Some(name.to_owned());
ctx.text(format!("name changed to: {}", name));
ctx.text(format!("name changed to: {name}"));
} else {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", msg)),
_ => ctx.text(format!("!!! unknown command: {msg:?}")),
}
return;

View File

@ -40,23 +40,23 @@ async fn main() {
Some(msg) = framed.next() => {
match msg {
Ok(codec::ChatResponse::Message(ref msg)) => {
println!("message: {}", msg);
println!("message: {msg}");
}
Ok(codec::ChatResponse::Joined(ref msg)) => {
println!("!!! joined: {}", msg);
println!("!!! joined: {msg}");
}
Ok(codec::ChatResponse::Rooms(rooms)) => {
println!("!!! Available rooms:");
for room in rooms {
println!("{}", room);
println!("{room}");
}
}
// respond to pings with a "pong"
Ok(codec::ChatResponse::Ping) => { framed.send(codec::ChatRequest::Ping).await.unwrap(); },
_ => { eprintln!("{:?}", msg); }
_ => { eprintln!("{msg:?}"); }
}
}

View File

@ -110,7 +110,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
Ok(msg) => msg,
};
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
match msg {
ws::Message::Ping(msg) => {
self.hb = Instant::now();
@ -168,11 +168,11 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
_ => ctx.text(format!("!!! unknown command: {m:?}")),
}
} else {
let msg = if let Some(ref name) = self.name {
format!("{}: {}", name, m)
format!("{name}: {m}")
} else {
m.to_owned()
};

View File

@ -102,7 +102,7 @@ impl StreamHandler<Result<ChatRequest, io::Error>> for ChatSession {
// so actor wont receive any new messages until it get list of rooms back
}
Ok(ChatRequest::Join(name)) => {
println!("Join to room: {}", name);
println!("Join to room: {name}");
self.room = name.clone();
self.addr.do_send(server::Join {
id: self.id,
@ -112,7 +112,7 @@ impl StreamHandler<Result<ChatRequest, io::Error>> for ChatSession {
}
Ok(ChatRequest::Message(message)) => {
// send message to chat server
println!("Peer message: {}", message);
println!("Peer message: {message}");
self.addr.do_send(server::Message {
id: self.id,
msg: message,

View File

@ -42,7 +42,7 @@ async fn chat_route(
/// Displays state
async fn get_count(count: web::Data<AtomicUsize>) -> impl Responder {
let current_count = count.load(Ordering::SeqCst);
format!("Visitors: {}", current_count)
format!("Visitors: {current_count}")
}
#[actix_web::main]

View File

@ -135,7 +135,7 @@ impl Handler<Connect> for ChatServer {
.insert(id);
let count = self.visitor_count.fetch_add(1, Ordering::SeqCst);
self.send_message("Main", &format!("Total visitors {}", count), 0);
self.send_message("Main", &format!("Total visitors {count}"), 0);
// send id back
id

View File

@ -114,7 +114,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
Ok(msg) => msg,
};
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
match msg {
ws::Message::Ping(msg) => {
self.hb = Instant::now();
@ -172,11 +172,11 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
ctx.text("!!! name is required");
}
}
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
_ => ctx.text(format!("!!! unknown command: {m:?}")),
}
} else {
let msg = if let Some(ref name) = self.name {
format!("{}: {}", name, m)
format!("{name}: {m}")
} else {
m.to_owned()
};

View File

@ -44,7 +44,7 @@ async fn main() {
match msg {
Ok(ws::Frame::Text(txt)) => {
// log echoed messages from server
log::info!("Server: {:?}", txt)
log::info!("Server: {txt:?}")
}
Ok(ws::Frame::Ping(_)) => {

View File

@ -57,7 +57,7 @@ impl Actor for MyWebSocket {
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWebSocket {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
// process websocket messages
println!("WS: {:?}", msg);
println!("WS: {msg:?}");
match msg {
Ok(ws::Message::Ping(msg)) => {
self.hb = Instant::now();