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:
parent
912de4aa46
commit
db5f00e771
@ -7,7 +7,7 @@ use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
|
|||||||
/// simple handle
|
/// simple handle
|
||||||
async fn success(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpResponse {
|
async fn success(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpResponse {
|
||||||
let mut e = enforcer.write().await;
|
let mut e = enforcer.write().await;
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
assert_eq!(vec!["data2_admin"], e.get_roles_for_user("alice", None));
|
assert_eq!(vec!["data2_admin"], e.get_roles_for_user("alice", None));
|
||||||
|
|
||||||
HttpResponse::Ok().body("Success: alice is data2_admin.")
|
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 {
|
async fn fail(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpResponse {
|
||||||
let mut e = enforcer.write().await;
|
let mut e = enforcer.write().await;
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
assert_eq!(vec!["data1_admin"], e.get_roles_for_user("alice", None));
|
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.
|
HttpResponse::Ok().body("Fail: alice is not data1_admin.") // In fact, it can't be displayed.
|
||||||
|
@ -10,12 +10,12 @@ use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Result};
|
|||||||
|
|
||||||
/// simple index handler with session
|
/// simple index handler with session
|
||||||
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
|
async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
|
||||||
log::info!("{:?}", req);
|
log::info!("{req:?}");
|
||||||
|
|
||||||
// RequestSession trait is used for session access
|
// RequestSession trait is used for session access
|
||||||
let mut counter = 1;
|
let mut counter = 1;
|
||||||
if let Some(count) = session.get::<i32>("counter")? {
|
if let Some(count) = session.get::<i32>("counter")? {
|
||||||
log::info!("SESSION value: {}", count);
|
log::info!("SESSION value: {count}");
|
||||||
counter = count + 1;
|
counter = count + 1;
|
||||||
session.insert("counter", counter)?;
|
session.insert("counter", counter)?;
|
||||||
} else {
|
} else {
|
||||||
|
@ -65,7 +65,7 @@ async fn logout(session: Session) -> Result<String> {
|
|||||||
let id: Option<String> = session.get("user_id")?;
|
let id: Option<String> = session.get("user_id")?;
|
||||||
if let Some(x) = id {
|
if let Some(x) = id {
|
||||||
session.purge();
|
session.purge();
|
||||||
Ok(format!("Logged out: {}", x))
|
Ok(format!("Logged out: {x}"))
|
||||||
} else {
|
} else {
|
||||||
Ok("Could not log out anonymous user".into())
|
Ok("Could not log out anonymous user".into())
|
||||||
}
|
}
|
||||||
|
@ -22,12 +22,12 @@ async fn favicon() -> Result<impl Responder> {
|
|||||||
/// simple index handler
|
/// simple index handler
|
||||||
#[get("/welcome")]
|
#[get("/welcome")]
|
||||||
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
|
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
|
|
||||||
// session
|
// session
|
||||||
let mut counter = 1;
|
let mut counter = 1;
|
||||||
if let Some(count) = session.get::<i32>("counter")? {
|
if let Some(count) = session.get::<i32>("counter")? {
|
||||||
println!("SESSION value: {}", count);
|
println!("SESSION value: {count}");
|
||||||
counter = count + 1;
|
counter = count + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,7 +63,7 @@ async fn response_body(path: web::Path<String>) -> HttpResponse {
|
|||||||
|
|
||||||
/// handler with path parameters like `/user/{name}/`
|
/// handler with path parameters like `/user/{name}/`
|
||||||
async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {
|
async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
|
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.content_type(ContentType::plaintext())
|
.content_type(ContentType::plaintext())
|
||||||
@ -110,7 +110,7 @@ async fn main() -> io::Result<()> {
|
|||||||
// redirect
|
// redirect
|
||||||
.service(
|
.service(
|
||||||
web::resource("/").route(web::get().to(|req: HttpRequest| async move {
|
web::resource("/").route(web::get().to(|req: HttpRequest| async move {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
HttpResponse::Found()
|
HttpResponse::Found()
|
||||||
.insert_header((header::LOCATION, "static/welcome.html"))
|
.insert_header((header::LOCATION, "static/welcome.html"))
|
||||||
.finish()
|
.finish()
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
|
use actix_web::{middleware, web, App, HttpRequest, HttpServer};
|
||||||
|
|
||||||
async fn index(req: HttpRequest) -> &'static str {
|
async fn index(req: HttpRequest) -> &'static str {
|
||||||
println!("REQ: {:?}", req);
|
println!("REQ: {req:?}");
|
||||||
"Hello world!"
|
"Hello world!"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -36,7 +36,7 @@ async fn index(
|
|||||||
counter_atomic: Data<AtomicUsize>,
|
counter_atomic: Data<AtomicUsize>,
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
) -> HttpResponse {
|
) -> HttpResponse {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
|
|
||||||
// Increment the counters
|
// Increment the counters
|
||||||
*counter_mutex.lock().unwrap() += 1;
|
*counter_mutex.lock().unwrap() += 1;
|
||||||
|
@ -80,7 +80,7 @@ pub async fn update(
|
|||||||
"put" => toggle(db, params).await,
|
"put" => toggle(db, params).await,
|
||||||
"delete" => delete(db, params, session).await,
|
"delete" => delete(db, params, session).await,
|
||||||
unsupported_method => {
|
unsupported_method => {
|
||||||
let msg = format!("Unsupported HTTP method: {}", unsupported_method);
|
let msg = format!("Unsupported HTTP method: {unsupported_method}");
|
||||||
Err(error::ErrorBadRequest(msg))
|
Err(error::ErrorBadRequest(msg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ pub struct Info {
|
|||||||
|
|
||||||
#[post("/user/info")]
|
#[post("/user/info")]
|
||||||
pub async fn info(info: web::Json<Info>) -> web::Json<Info> {
|
pub async fn info(info: web::Json<Info>) -> web::Json<Info> {
|
||||||
println!("=========={:?}=========", info);
|
println!("=========={info:?}=========");
|
||||||
web::Json(Info {
|
web::Json(Info {
|
||||||
username: info.username.clone(),
|
username: info.username.clone(),
|
||||||
email: info.email.clone(),
|
email: info.email.clone(),
|
||||||
|
@ -36,7 +36,7 @@ async fn get_user(
|
|||||||
if let Some(user) = user {
|
if let Some(user) = user {
|
||||||
Ok(HttpResponse::Ok().json(user))
|
Ok(HttpResponse::Ok().json(user))
|
||||||
} else {
|
} 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)
|
Ok(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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(Some(user)) => HttpResponse::Ok().json(user),
|
||||||
Ok(None) => {
|
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()),
|
Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
|
||||||
}
|
}
|
||||||
|
@ -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())
|
Ok(HttpResponse::InternalServerError().finish())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -62,7 +62,7 @@ async fn handle_post_2(
|
|||||||
|
|
||||||
/// Request and POST Params
|
/// Request and POST Params
|
||||||
async fn handle_post_3(req: HttpRequest, params: web::Form<MyParams>) -> impl Responder {
|
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()
|
HttpResponse::Ok()
|
||||||
.content_type("text/plain")
|
.content_type("text/plain")
|
||||||
|
@ -81,9 +81,9 @@ async fn main() -> std::io::Result<()> {
|
|||||||
let aws_s3_bucket_name =
|
let aws_s3_bucket_name =
|
||||||
env::var("AWS_S3_BUCKET_NAME").expect("AWS_S3_BUCKET_NAME must be set");
|
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_access_key_id: {aws_access_key_id}");
|
||||||
log::info!("aws_secret_access_key: {}", aws_secret_access_key);
|
log::info!("aws_secret_access_key: {aws_secret_access_key}");
|
||||||
log::info!("aws_s3_bucket_name: {}", aws_s3_bucket_name);
|
log::info!("aws_s3_bucket_name: {aws_s3_bucket_name}");
|
||||||
|
|
||||||
std::fs::create_dir_all("./tmp").unwrap();
|
std::fs::create_dir_all("./tmp").unwrap();
|
||||||
|
|
||||||
|
@ -24,10 +24,9 @@ impl Client {
|
|||||||
|
|
||||||
pub fn url(&self, key: &str) -> String {
|
pub fn url(&self, key: &str) -> String {
|
||||||
format!(
|
format!(
|
||||||
"https://{}.s3.{}.amazonaws.com/{}",
|
"https://{}.s3.{}.amazonaws.com/{key}",
|
||||||
std::env::var("AWS_S3_BUCKET_NAME").unwrap(),
|
std::env::var("AWS_S3_BUCKET_NAME").unwrap(),
|
||||||
std::env::var("AWS_REGION").unwrap(),
|
std::env::var("AWS_REGION").unwrap(),
|
||||||
key
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -39,7 +39,7 @@ impl Tmpfile {
|
|||||||
fn new(filename: &str) -> Tmpfile {
|
fn new(filename: &str) -> Tmpfile {
|
||||||
Tmpfile {
|
Tmpfile {
|
||||||
name: filename.to_string(),
|
name: filename.to_string(),
|
||||||
tmp_path: format!("./tmp/{}", filename),
|
tmp_path: format!("./tmp/{filename}"),
|
||||||
s3_key: "".to_string(),
|
s3_key: "".to_string(),
|
||||||
s3_url: "".to_string(),
|
s3_url: "".to_string(),
|
||||||
}
|
}
|
||||||
@ -51,7 +51,7 @@ impl Tmpfile {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn s3_upload(&mut self, s3_upload_key: String) {
|
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();
|
self.s3_key = key.clone();
|
||||||
let url: String = Client::new().put_object(&self.tmp_path, &key.clone()).await;
|
let url: String = Client::new().put_object(&self.tmp_path, &key.clone()).await;
|
||||||
self.s3_url = url;
|
self.s3_url = url;
|
||||||
|
@ -14,7 +14,7 @@ async fn save_file(mut payload: Multipart) -> Result<HttpResponse, Error> {
|
|||||||
let filename = content_disposition
|
let filename = content_disposition
|
||||||
.get_filename()
|
.get_filename()
|
||||||
.map_or_else(|| Uuid::new_v4().to_string(), sanitize_filename::sanitize);
|
.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
|
// File::create is blocking operation, use threadpool
|
||||||
let mut f = web::block(|| std::fs::File::create(filepath)).await??;
|
let mut f = web::block(|| std::fs::File::create(filepath)).await??;
|
||||||
|
@ -59,7 +59,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
.next()
|
.next()
|
||||||
.expect("given forwarding address was not valid");
|
.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();
|
let forward_url = Url::parse(&forward_url).unwrap();
|
||||||
|
|
||||||
log::info!(
|
log::info!(
|
||||||
|
@ -90,7 +90,7 @@ pub async fn gen_tls_cert(user_email: &str, user_domain: &str) -> anyhow::Result
|
|||||||
let proof = chall.http_proof()?;
|
let proof = chall.http_proof()?;
|
||||||
|
|
||||||
// Place the file/contents in the correct place.
|
// Place the file/contents in the correct place.
|
||||||
let path = format!("acme-challenge/{}", token);
|
let path = format!("acme-challenge/{token}");
|
||||||
fs::write(&path, &proof)?;
|
fs::write(&path, &proof)?;
|
||||||
|
|
||||||
// After the file is accessible from the web, the calls
|
// After the file is accessible from the web, the calls
|
||||||
|
@ -5,7 +5,7 @@ use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
|||||||
|
|
||||||
/// simple handle
|
/// simple handle
|
||||||
async fn index(req: HttpRequest) -> Result<HttpResponse, Error> {
|
async fn index(req: HttpRequest) -> Result<HttpResponse, Error> {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
Ok(HttpResponse::Ok()
|
Ok(HttpResponse::Ok()
|
||||||
.content_type("text/plain")
|
.content_type("text/plain")
|
||||||
.body("Welcome!"))
|
.body("Welcome!"))
|
||||||
|
@ -11,7 +11,7 @@ use rustls_pemfile::{certs, pkcs8_private_keys};
|
|||||||
|
|
||||||
/// simple handle
|
/// simple handle
|
||||||
async fn index(req: HttpRequest) -> HttpResponse {
|
async fn index(req: HttpRequest) -> HttpResponse {
|
||||||
debug!("{:?}", req);
|
debug!("{req:?}");
|
||||||
|
|
||||||
HttpResponse::Ok().content_type(ContentType::html()).body(
|
HttpResponse::Ok().content_type(ContentType::html()).body(
|
||||||
"<!DOCTYPE html><html><body>\
|
"<!DOCTYPE html><html><body>\
|
||||||
|
@ -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();
|
let body: HttpBinResponse = serde_json::from_slice(&body).unwrap();
|
||||||
|
|
||||||
println!("{:?}", body);
|
println!("{body:?}");
|
||||||
|
|
||||||
Ok(body.json)
|
Ok(body.json)
|
||||||
}
|
}
|
||||||
|
@ -17,8 +17,8 @@ async fn index(item: web::Json<MyObj>) -> HttpResponse {
|
|||||||
|
|
||||||
/// This handler uses json extractor with limit
|
/// This handler uses json extractor with limit
|
||||||
async fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
|
async fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
|
||||||
println!("request: {:?}", req);
|
println!("request: {req:?}");
|
||||||
println!("model: {:?}", item);
|
println!("model: {item:?}");
|
||||||
|
|
||||||
HttpResponse::Ok().json(item.0) // <- send json response
|
HttpResponse::Ok().json(item.0) // <- send json response
|
||||||
}
|
}
|
||||||
|
@ -70,7 +70,7 @@ async fn rpc_select(
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(ok) => Ok(Value::from(ok)),
|
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" => {
|
"get" => {
|
||||||
|
@ -41,7 +41,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
.wrap_fn(|sreq, srv| {
|
.wrap_fn(|sreq, srv| {
|
||||||
let host = sreq.connection_info().host().to_owned();
|
let host = sreq.connection_info().host().to_owned();
|
||||||
let uri = sreq.uri().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
|
// 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
|
// handle the request and if it's "http" then a response with redirect status code
|
||||||
|
@ -58,7 +58,7 @@ where
|
|||||||
body.extend_from_slice(&chunk?);
|
body.extend_from_slice(&chunk?);
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("request body: {:?}", body);
|
println!("request body: {body:?}");
|
||||||
let res = svc.call(req).await?;
|
let res = svc.call(req).await?;
|
||||||
|
|
||||||
println!("response: {:?}", res.headers());
|
println!("response: {:?}", res.headers());
|
||||||
|
@ -12,7 +12,7 @@ pub struct MyObj {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
|
async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
|
||||||
log::info!("model: {:?}", msg);
|
log::info!("model: {msg:?}");
|
||||||
HttpResponse::Ok().protobuf(msg.0) // <- send response
|
HttpResponse::Ok().protobuf(msg.0) // <- send response
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,7 +7,7 @@ use std::{sync::mpsc, thread, time};
|
|||||||
use actix_web::{dev::ServerHandle, middleware, rt, web, App, HttpRequest, HttpServer};
|
use actix_web::{dev::ServerHandle, middleware, rt, web, App, HttpRequest, HttpServer};
|
||||||
|
|
||||||
async fn index(req: HttpRequest) -> &'static str {
|
async fn index(req: HttpRequest) -> &'static str {
|
||||||
log::info!("REQ: {:?}", req);
|
log::info!("REQ: {req:?}");
|
||||||
"Hello world!"
|
"Hello world!"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -75,9 +75,8 @@ impl Handler<JoinRoom> for WsChatServer {
|
|||||||
|
|
||||||
let id = self.add_client_to_room(&room_name, None, client);
|
let id = self.add_client_to_room(&room_name, None, client);
|
||||||
let join_msg = format!(
|
let join_msg = format!(
|
||||||
"{} joined {}",
|
"{} joined {room_name}",
|
||||||
client_name.unwrap_or_else(|| "anon".to_string()),
|
client_name.unwrap_or_else(|| "anon".to_string()),
|
||||||
room_name
|
|
||||||
);
|
);
|
||||||
|
|
||||||
self.send_chat_message(&room_name, &join_msg, id);
|
self.send_chat_message(&room_name, &join_msg, id);
|
||||||
|
@ -63,9 +63,8 @@ impl WsChatSession {
|
|||||||
|
|
||||||
pub fn send_msg(&self, msg: &str) {
|
pub fn send_msg(&self, msg: &str) {
|
||||||
let content = format!(
|
let content = format!(
|
||||||
"{}: {}",
|
"{}: {msg}",
|
||||||
self.name.clone().unwrap_or_else(|| "anon".to_string()),
|
self.name.clone().unwrap_or_else(|| "anon".to_string()),
|
||||||
msg
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let msg = SendMessage(self.room.clone(), self.id, content);
|
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,
|
Ok(msg) => msg,
|
||||||
};
|
};
|
||||||
|
|
||||||
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
|
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
|
||||||
|
|
||||||
match msg {
|
match msg {
|
||||||
ws::Message::Text(text) => {
|
ws::Message::Text(text) => {
|
||||||
@ -133,13 +132,13 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
|||||||
Some("/name") => {
|
Some("/name") => {
|
||||||
if let Some(name) = command.next() {
|
if let Some(name) = command.next() {
|
||||||
self.name = Some(name.to_owned());
|
self.name = Some(name.to_owned());
|
||||||
ctx.text(format!("name changed to: {}", name));
|
ctx.text(format!("name changed to: {name}"));
|
||||||
} else {
|
} else {
|
||||||
ctx.text("!!! name is required");
|
ctx.text("!!! name is required");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => ctx.text(format!("!!! unknown command: {:?}", msg)),
|
_ => ctx.text(format!("!!! unknown command: {msg:?}")),
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
@ -40,23 +40,23 @@ async fn main() {
|
|||||||
Some(msg) = framed.next() => {
|
Some(msg) = framed.next() => {
|
||||||
match msg {
|
match msg {
|
||||||
Ok(codec::ChatResponse::Message(ref msg)) => {
|
Ok(codec::ChatResponse::Message(ref msg)) => {
|
||||||
println!("message: {}", msg);
|
println!("message: {msg}");
|
||||||
}
|
}
|
||||||
Ok(codec::ChatResponse::Joined(ref msg)) => {
|
Ok(codec::ChatResponse::Joined(ref msg)) => {
|
||||||
println!("!!! joined: {}", msg);
|
println!("!!! joined: {msg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(codec::ChatResponse::Rooms(rooms)) => {
|
Ok(codec::ChatResponse::Rooms(rooms)) => {
|
||||||
println!("!!! Available rooms:");
|
println!("!!! Available rooms:");
|
||||||
for room in rooms {
|
for room in rooms {
|
||||||
println!("{}", room);
|
println!("{room}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// respond to pings with a "pong"
|
// respond to pings with a "pong"
|
||||||
Ok(codec::ChatResponse::Ping) => { framed.send(codec::ChatRequest::Ping).await.unwrap(); },
|
Ok(codec::ChatResponse::Ping) => { framed.send(codec::ChatRequest::Ping).await.unwrap(); },
|
||||||
|
|
||||||
_ => { eprintln!("{:?}", msg); }
|
_ => { eprintln!("{msg:?}"); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -110,7 +110,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
|||||||
Ok(msg) => msg,
|
Ok(msg) => msg,
|
||||||
};
|
};
|
||||||
|
|
||||||
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
|
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
|
||||||
match msg {
|
match msg {
|
||||||
ws::Message::Ping(msg) => {
|
ws::Message::Ping(msg) => {
|
||||||
self.hb = Instant::now();
|
self.hb = Instant::now();
|
||||||
@ -168,11 +168,11 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
|||||||
ctx.text("!!! name is required");
|
ctx.text("!!! name is required");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
|
_ => ctx.text(format!("!!! unknown command: {m:?}")),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let msg = if let Some(ref name) = self.name {
|
let msg = if let Some(ref name) = self.name {
|
||||||
format!("{}: {}", name, m)
|
format!("{name}: {m}")
|
||||||
} else {
|
} else {
|
||||||
m.to_owned()
|
m.to_owned()
|
||||||
};
|
};
|
||||||
|
@ -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
|
// so actor wont receive any new messages until it get list of rooms back
|
||||||
}
|
}
|
||||||
Ok(ChatRequest::Join(name)) => {
|
Ok(ChatRequest::Join(name)) => {
|
||||||
println!("Join to room: {}", name);
|
println!("Join to room: {name}");
|
||||||
self.room = name.clone();
|
self.room = name.clone();
|
||||||
self.addr.do_send(server::Join {
|
self.addr.do_send(server::Join {
|
||||||
id: self.id,
|
id: self.id,
|
||||||
@ -112,7 +112,7 @@ impl StreamHandler<Result<ChatRequest, io::Error>> for ChatSession {
|
|||||||
}
|
}
|
||||||
Ok(ChatRequest::Message(message)) => {
|
Ok(ChatRequest::Message(message)) => {
|
||||||
// send message to chat server
|
// send message to chat server
|
||||||
println!("Peer message: {}", message);
|
println!("Peer message: {message}");
|
||||||
self.addr.do_send(server::Message {
|
self.addr.do_send(server::Message {
|
||||||
id: self.id,
|
id: self.id,
|
||||||
msg: message,
|
msg: message,
|
||||||
|
@ -42,7 +42,7 @@ async fn chat_route(
|
|||||||
/// Displays state
|
/// Displays state
|
||||||
async fn get_count(count: web::Data<AtomicUsize>) -> impl Responder {
|
async fn get_count(count: web::Data<AtomicUsize>) -> impl Responder {
|
||||||
let current_count = count.load(Ordering::SeqCst);
|
let current_count = count.load(Ordering::SeqCst);
|
||||||
format!("Visitors: {}", current_count)
|
format!("Visitors: {current_count}")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
|
@ -135,7 +135,7 @@ impl Handler<Connect> for ChatServer {
|
|||||||
.insert(id);
|
.insert(id);
|
||||||
|
|
||||||
let count = self.visitor_count.fetch_add(1, Ordering::SeqCst);
|
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
|
// send id back
|
||||||
id
|
id
|
||||||
|
@ -114,7 +114,7 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
|||||||
Ok(msg) => msg,
|
Ok(msg) => msg,
|
||||||
};
|
};
|
||||||
|
|
||||||
log::debug!("WEBSOCKET MESSAGE: {:?}", msg);
|
log::debug!("WEBSOCKET MESSAGE: {msg:?}");
|
||||||
match msg {
|
match msg {
|
||||||
ws::Message::Ping(msg) => {
|
ws::Message::Ping(msg) => {
|
||||||
self.hb = Instant::now();
|
self.hb = Instant::now();
|
||||||
@ -172,11 +172,11 @@ impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for WsChatSession {
|
|||||||
ctx.text("!!! name is required");
|
ctx.text("!!! name is required");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
|
_ => ctx.text(format!("!!! unknown command: {m:?}")),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let msg = if let Some(ref name) = self.name {
|
let msg = if let Some(ref name) = self.name {
|
||||||
format!("{}: {}", name, m)
|
format!("{name}: {m}")
|
||||||
} else {
|
} else {
|
||||||
m.to_owned()
|
m.to_owned()
|
||||||
};
|
};
|
||||||
|
@ -44,7 +44,7 @@ async fn main() {
|
|||||||
match msg {
|
match msg {
|
||||||
Ok(ws::Frame::Text(txt)) => {
|
Ok(ws::Frame::Text(txt)) => {
|
||||||
// log echoed messages from server
|
// log echoed messages from server
|
||||||
log::info!("Server: {:?}", txt)
|
log::info!("Server: {txt:?}")
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(ws::Frame::Ping(_)) => {
|
Ok(ws::Frame::Ping(_)) => {
|
||||||
|
@ -57,7 +57,7 @@ impl Actor for MyWebSocket {
|
|||||||
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> 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) {
|
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
||||||
// process websocket messages
|
// process websocket messages
|
||||||
println!("WS: {:?}", msg);
|
println!("WS: {msg:?}");
|
||||||
match msg {
|
match msg {
|
||||||
Ok(ws::Message::Ping(msg)) => {
|
Ok(ws::Message::Ping(msg)) => {
|
||||||
self.hb = Instant::now();
|
self.hb = Instant::now();
|
||||||
|
Loading…
Reference in New Issue
Block a user