mirror of
https://github.com/tokio-rs/axum.git
synced 2025-03-26 00:27:01 +01:00
Use inline format args (#2232)
This commit is contained in:
parent
a9822ec80b
commit
786329d85d
35 changed files with 72 additions and 83 deletions
axum-core/src
axum-extra/src
axum/src
docs
handler
routing
examples
chat/src
customize-path-rejection/src
diesel-async-postgres/src
diesel-postgres/src
graceful-shutdown/src
http-proxy/src
jwt/src
key-value-store/src
multipart-form/src
oauth/src
print-request-response/src
query-params-with-empty-strings/src
rest-grpc-multiplex/src
reverse-proxy/src
templates/src
testing/src
tls-graceful-shutdown/src
tls-rustls/src
todos/src
unix-domain-socket/src
validator/src
versioning/src
websockets/src
|
@ -193,7 +193,7 @@ macro_rules! __composite_rejection {
|
|||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
$(
|
||||
Self::$variant(inner) => write!(f, "{}", inner),
|
||||
Self::$variant(inner) => write!(f, "{inner}"),
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,7 +33,7 @@ pin_project! {
|
|||
/// let file = File::open("Cargo.toml")
|
||||
/// .await
|
||||
/// .map_err(|err| {
|
||||
/// (StatusCode::NOT_FOUND, format!("File not found: {}", err))
|
||||
/// (StatusCode::NOT_FOUND, format!("File not found: {err}"))
|
||||
/// })?;
|
||||
///
|
||||
/// let headers = [(CONTENT_TYPE, "text/x-toml")];
|
||||
|
|
|
@ -83,7 +83,7 @@ impl IntoResponse for FormRejection {
|
|||
Self::RawFormRejection(inner) => inner.into_response(),
|
||||
Self::FailedToDeserializeForm(inner) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("Failed to deserialize form: {}", inner),
|
||||
format!("Failed to deserialize form: {inner}"),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
|
|
|
@ -89,7 +89,7 @@ impl IntoResponse for QueryRejection {
|
|||
match self {
|
||||
Self::FailedToDeserializeQueryString(inner) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("Failed to deserialize query string: {}", inner),
|
||||
format!("Failed to deserialize query string: {inner}"),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
|
|
|
@ -92,7 +92,7 @@ let app = Router::new().route_service(
|
|||
async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Something went wrong: {}", err),
|
||||
format!("Something went wrong: {err}"),
|
||||
)
|
||||
}
|
||||
# let _: Router = app;
|
||||
|
@ -133,7 +133,7 @@ async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) {
|
|||
} else {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", err),
|
||||
format!("Unhandled internal error: {err}"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@ -174,7 +174,7 @@ async fn handle_timeout_error(
|
|||
) -> (StatusCode, String) {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("`{} {}` failed with {}", method, uri, err),
|
||||
format!("`{method} {uri}` failed with {err}"),
|
||||
)
|
||||
}
|
||||
# let _: Router = app;
|
||||
|
|
|
@ -16,7 +16,7 @@ let handler = get(|| async {}).fallback(fallback);
|
|||
let app = Router::new().route("/", handler);
|
||||
|
||||
async fn fallback(method: Method, uri: Uri) -> (StatusCode, String) {
|
||||
(StatusCode::NOT_FOUND, format!("`{}` not allowed for {}", method, uri))
|
||||
(StatusCode::NOT_FOUND, format!("`{method}` not allowed for {uri}"))
|
||||
}
|
||||
# async {
|
||||
# hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
|
||||
|
|
|
@ -16,7 +16,7 @@ let app = Router::new()
|
|||
.fallback(fallback);
|
||||
|
||||
async fn fallback(uri: Uri) -> (StatusCode, String) {
|
||||
(StatusCode::NOT_FOUND, format!("No route for {}", uri))
|
||||
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
|
||||
}
|
||||
# let _: Router = app;
|
||||
```
|
||||
|
|
|
@ -17,7 +17,7 @@ use std::net::SocketAddr;
|
|||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
|
||||
format!("Hello {}", addr)
|
||||
format!("Hello {addr}")
|
||||
}
|
||||
|
||||
# async {
|
||||
|
@ -41,7 +41,7 @@ let app = Router::new().route("/", get(handler));
|
|||
async fn handler(
|
||||
ConnectInfo(my_connect_info): ConnectInfo<MyConnectInfo>,
|
||||
) -> String {
|
||||
format!("Hello {:?}", my_connect_info)
|
||||
format!("Hello {my_connect_info:?}")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
|
@ -84,7 +84,7 @@ impl<H, T, S> HandlerService<H, T, S> {
|
|||
/// ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
/// State(state): State<AppState>,
|
||||
/// ) -> String {
|
||||
/// format!("Hello {}", addr)
|
||||
/// format!("Hello {addr}")
|
||||
/// }
|
||||
///
|
||||
/// let app = handler.with_state(AppState {});
|
||||
|
|
|
@ -619,7 +619,7 @@ impl MethodRouter<(), Infallible> {
|
|||
/// use std::net::SocketAddr;
|
||||
///
|
||||
/// async fn handler(method: Method, uri: Uri, body: String) -> String {
|
||||
/// format!("received `{} {}` with body `{:?}`", method, uri, body)
|
||||
/// format!("received `{method} {uri}` with body `{body:?}`")
|
||||
/// }
|
||||
///
|
||||
/// let router = get(handler).post(handler);
|
||||
|
@ -650,7 +650,7 @@ impl MethodRouter<(), Infallible> {
|
|||
/// use std::net::SocketAddr;
|
||||
///
|
||||
/// async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
|
||||
/// format!("Hello {}", addr)
|
||||
/// format!("Hello {addr}")
|
||||
/// }
|
||||
///
|
||||
/// let router = get(handler).post(handler);
|
||||
|
|
|
@ -945,7 +945,7 @@ async fn state_isnt_cloned_too_much() {
|
|||
.filter(|line| line.contains("axum") || line.contains("./src"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
println!("AppState::Clone:\n===============\n{}\n", bt);
|
||||
println!("AppState::Clone:\n===============\n{bt}\n");
|
||||
COUNT.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -100,8 +100,8 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
|
|||
let mut rx = state.tx.subscribe();
|
||||
|
||||
// Now send the "joined" message to all subscribers.
|
||||
let msg = format!("{} joined.", username);
|
||||
tracing::debug!("{}", msg);
|
||||
let msg = format!("{username} joined.");
|
||||
tracing::debug!("{msg}");
|
||||
let _ = state.tx.send(msg);
|
||||
|
||||
// Spawn the first task that will receive broadcast messages and send text
|
||||
|
@ -124,7 +124,7 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
|
|||
let mut recv_task = tokio::spawn(async move {
|
||||
while let Some(Ok(Message::Text(text))) = receiver.next().await {
|
||||
// Add username before message.
|
||||
let _ = tx.send(format!("{}: {}", name, text));
|
||||
let _ = tx.send(format!("{name}: {text}"));
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -135,8 +135,8 @@ async fn websocket(stream: WebSocket, state: Arc<AppState>) {
|
|||
};
|
||||
|
||||
// Send "user left" message (similar to "joined" above).
|
||||
let msg = format!("{} left.", username);
|
||||
tracing::debug!("{}", msg);
|
||||
let msg = format!("{username} left.");
|
||||
tracing::debug!("{msg}");
|
||||
let _ = state.tx.send(msg);
|
||||
|
||||
// Remove username from map so new clients can take it again.
|
||||
|
|
|
@ -109,7 +109,7 @@ where
|
|||
},
|
||||
|
||||
_ => PathError {
|
||||
message: format!("Unhandled deserialization error: {}", kind),
|
||||
message: format!("Unhandled deserialization error: {kind}"),
|
||||
location: None,
|
||||
},
|
||||
};
|
||||
|
@ -126,7 +126,7 @@ where
|
|||
_ => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
PathError {
|
||||
message: format!("Unhandled path rejection: {}", rejection),
|
||||
message: format!("Unhandled path rejection: {rejection}"),
|
||||
location: None,
|
||||
},
|
||||
),
|
||||
|
|
|
@ -76,7 +76,7 @@ async fn main() {
|
|||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
|
|
@ -84,7 +84,7 @@ async fn main() {
|
|||
|
||||
// run it with hyper
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ async fn main() {
|
|||
|
||||
// run it
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
println!("listening on {}", addr);
|
||||
println!("listening on {addr}");
|
||||
hyper::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
|
|
|
@ -51,7 +51,7 @@ async fn main() {
|
|||
});
|
||||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
hyper::Server::bind(&addr)
|
||||
.http1_preserve_header_case(true)
|
||||
.http1_title_case_headers(true)
|
||||
|
@ -68,10 +68,10 @@ async fn proxy(req: Request) -> Result<Response, hyper::Error> {
|
|||
match hyper::upgrade::on(req).await {
|
||||
Ok(upgraded) => {
|
||||
if let Err(e) = tunnel(upgraded, host_addr).await {
|
||||
tracing::warn!("server io error: {}", e);
|
||||
tracing::warn!("server io error: {e}");
|
||||
};
|
||||
}
|
||||
Err(e) => tracing::warn!("upgrade error: {}", e),
|
||||
Err(e) => tracing::warn!("upgrade error: {e}"),
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -92,11 +92,7 @@ async fn tunnel(mut upgraded: Upgraded, addr: String) -> std::io::Result<()> {
|
|||
let (from_client, from_server) =
|
||||
tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?;
|
||||
|
||||
tracing::debug!(
|
||||
"client wrote {} bytes and received {} bytes",
|
||||
from_client,
|
||||
from_server
|
||||
);
|
||||
tracing::debug!("client wrote {from_client} bytes and received {from_server} bytes");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -80,8 +80,7 @@ async fn main() {
|
|||
async fn protected(claims: Claims) -> Result<String, AuthError> {
|
||||
// Send the protected data to the user
|
||||
Ok(format!(
|
||||
"Welcome to the protected area :)\nYour data:\n{}",
|
||||
claims
|
||||
"Welcome to the protected area :)\nYour data:\n{claims}",
|
||||
))
|
||||
}
|
||||
|
||||
|
|
|
@ -143,6 +143,6 @@ async fn handle_error(error: BoxError) -> impl IntoResponse {
|
|||
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Cow::from(format!("Unhandled internal error: {}", error)),
|
||||
Cow::from(format!("Unhandled internal error: {error}")),
|
||||
)
|
||||
}
|
||||
|
|
|
@ -69,10 +69,7 @@ async fn accept_form(mut multipart: Multipart) {
|
|||
let data = field.bytes().await.unwrap();
|
||||
|
||||
println!(
|
||||
"Length of `{}` (`{}`: `{}`) is {} bytes",
|
||||
name,
|
||||
file_name,
|
||||
content_type,
|
||||
"Length of `{name}` (`{file_name}`: `{content_type}`) is {} bytes",
|
||||
data.len()
|
||||
);
|
||||
}
|
||||
|
|
|
@ -157,10 +157,7 @@ async fn discord_auth(State(client): State<BasicClient>) -> impl IntoResponse {
|
|||
|
||||
// Valid user session required. If there is none, redirect to the auth page
|
||||
async fn protected(user: User) -> impl IntoResponse {
|
||||
format!(
|
||||
"Welcome to the protected area :)\nHere's your info:\n{:?}",
|
||||
user
|
||||
)
|
||||
format!("Welcome to the protected area :)\nHere's your info:\n{user:?}")
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
|
@ -235,7 +232,7 @@ async fn login_authorized(
|
|||
.context("unexpected error retrieving cookie value")?;
|
||||
|
||||
// Build the cookie
|
||||
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie);
|
||||
let cookie = format!("{COOKIE_NAME}={cookie}; SameSite=Lax; Path=/");
|
||||
|
||||
// Set cookie
|
||||
let mut headers = HeaderMap::new();
|
||||
|
@ -273,9 +270,9 @@ where
|
|||
.map_err(|e| match *e.name() {
|
||||
header::COOKIE => match e.reason() {
|
||||
TypedHeaderRejectionReason::Missing => AuthRedirect,
|
||||
_ => panic!("unexpected error getting Cookie header(s): {}", e),
|
||||
_ => panic!("unexpected error getting Cookie header(s): {e}"),
|
||||
},
|
||||
_ => panic!("unexpected error getting cookies: {}", e),
|
||||
_ => panic!("unexpected error getting cookies: {e}"),
|
||||
})?;
|
||||
let session_cookie = cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?;
|
||||
|
||||
|
|
|
@ -63,13 +63,13 @@ where
|
|||
Err(err) => {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("failed to read {} body: {}", direction, err),
|
||||
format!("failed to read {direction} body: {err}"),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Ok(body) = std::str::from_utf8(&bytes) {
|
||||
tracing::debug!("{} body = {:?}", direction, body);
|
||||
tracing::debug!("{direction} body = {body:?}");
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
|
|
|
@ -22,7 +22,7 @@ fn app() -> Router {
|
|||
}
|
||||
|
||||
async fn handler(Query(params): Query<Params>) -> String {
|
||||
format!("{:?}", params)
|
||||
format!("{params:?}")
|
||||
}
|
||||
|
||||
/// See the tests below for which combinations of `foo` and `bar` result in
|
||||
|
@ -107,7 +107,7 @@ mod tests {
|
|||
let body = app()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(format!("/?{}", query))
|
||||
.uri(format!("/?{query}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
|
|
|
@ -74,7 +74,7 @@ async fn main() {
|
|||
let service = MultiplexService::new(rest, grpc);
|
||||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
hyper::Server::bind(&addr)
|
||||
.serve(tower::make::Shared::new(service))
|
||||
.await
|
||||
|
|
|
@ -42,7 +42,7 @@ async fn handler(State(client): State<Client>, mut req: Request) -> Result<Respo
|
|||
.map(|v| v.as_str())
|
||||
.unwrap_or(path);
|
||||
|
||||
let uri = format!("http://127.0.0.1:3000{}", path_query);
|
||||
let uri = format!("http://127.0.0.1:3000{path_query}");
|
||||
|
||||
*req.uri_mut() = Uri::try_from(uri).unwrap();
|
||||
|
||||
|
|
|
@ -57,7 +57,7 @@ where
|
|||
Ok(html) => Html(html).into_response(),
|
||||
Err(err) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Failed to render template. Error: {}", err),
|
||||
format!("Failed to render template. Error: {err}"),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
|
|
|
@ -140,7 +140,7 @@ mod tests {
|
|||
let response = client
|
||||
.request(
|
||||
Request::builder()
|
||||
.uri(format!("http://{}", addr))
|
||||
.uri(format!("http://{addr}"))
|
||||
.body(hyper::Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
|
|
|
@ -62,7 +62,7 @@ async fn main() {
|
|||
|
||||
// run https server
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
axum_server::bind_rustls(addr, config)
|
||||
.handle(handle)
|
||||
.serve(app.into_make_service())
|
||||
|
@ -130,7 +130,7 @@ async fn redirect_http_to_https(ports: Ports, signal: impl Future<Output = ()>)
|
|||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));
|
||||
//let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
tracing::debug!("listening on {}", &addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
hyper::Server::bind(&addr)
|
||||
.serve(redirect.into_make_service())
|
||||
.with_graceful_shutdown(signal)
|
||||
|
|
|
@ -55,7 +55,7 @@ async fn main() {
|
|||
|
||||
// run https server
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
tracing::debug!("listening on {addr}");
|
||||
axum_server::bind_rustls(addr, config)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
|
|
|
@ -57,7 +57,7 @@ async fn main() {
|
|||
} else {
|
||||
Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
format!("Unhandled internal error: {error}"),
|
||||
))
|
||||
}
|
||||
}))
|
||||
|
|
|
@ -94,7 +94,7 @@ mod unix {
|
|||
}
|
||||
|
||||
async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
|
||||
println!("new connection from `{:?}`", info);
|
||||
println!("new connection from `{info:?}`");
|
||||
|
||||
"Hello, World!"
|
||||
}
|
||||
|
|
|
@ -85,7 +85,7 @@ impl IntoResponse for ServerError {
|
|||
fn into_response(self) -> Response {
|
||||
match self {
|
||||
ServerError::ValidationError(_) => {
|
||||
let message = format!("Input validation error: [{}]", self).replace('\n', ", ");
|
||||
let message = format!("Input validation error: [{self}]").replace('\n', ", ");
|
||||
(StatusCode::BAD_REQUEST, message)
|
||||
}
|
||||
ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||
|
|
|
@ -37,7 +37,7 @@ async fn main() {
|
|||
}
|
||||
|
||||
async fn handler(version: Version) {
|
||||
println!("received request with version {:?}", version);
|
||||
println!("received request with version {version:?}");
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
|
@ -49,10 +49,10 @@ async fn main() {
|
|||
async fn spawn_client(who: usize) {
|
||||
let ws_stream = match connect_async(SERVER).await {
|
||||
Ok((stream, response)) => {
|
||||
println!("Handshake for client {} has been completed", who);
|
||||
println!("Handshake for client {who} has been completed");
|
||||
// This will be the HTTP response, same as with server this is the last moment we
|
||||
// can still access HTTP stuff.
|
||||
println!("Server response was {:?}", response);
|
||||
println!("Server response was {response:?}");
|
||||
stream
|
||||
}
|
||||
Err(e) => {
|
||||
|
@ -74,7 +74,7 @@ async fn spawn_client(who: usize) {
|
|||
for i in 1..30 {
|
||||
// In any websocket error, break loop.
|
||||
if sender
|
||||
.send(Message::Text(format!("Message number {}...", i)))
|
||||
.send(Message::Text(format!("Message number {i}...")))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
|
@ -86,7 +86,7 @@ async fn spawn_client(who: usize) {
|
|||
}
|
||||
|
||||
// When we are done we may want our client to close connection cleanly.
|
||||
println!("Sending close to {}...", who);
|
||||
println!("Sending close to {who}...");
|
||||
if let Err(e) = sender
|
||||
.send(Message::Close(Some(CloseFrame {
|
||||
code: CloseCode::Normal,
|
||||
|
@ -94,7 +94,7 @@ async fn spawn_client(who: usize) {
|
|||
})))
|
||||
.await
|
||||
{
|
||||
println!("Could not send Close due to {:?}, probably it is ok?", e);
|
||||
println!("Could not send Close due to {e:?}, probably it is ok?");
|
||||
};
|
||||
});
|
||||
|
||||
|
@ -124,7 +124,7 @@ async fn spawn_client(who: usize) {
|
|||
fn process_message(msg: Message, who: usize) -> ControlFlow<(), ()> {
|
||||
match msg {
|
||||
Message::Text(t) => {
|
||||
println!(">>> {} got str: {:?}", who, t);
|
||||
println!(">>> {who} got str: {t:?}");
|
||||
}
|
||||
Message::Binary(d) => {
|
||||
println!(">>> {} got {} bytes: {:?}", who, d.len(), d);
|
||||
|
@ -136,19 +136,19 @@ fn process_message(msg: Message, who: usize) -> ControlFlow<(), ()> {
|
|||
who, cf.code, cf.reason
|
||||
);
|
||||
} else {
|
||||
println!(">>> {} somehow got close message without CloseFrame", who);
|
||||
println!(">>> {who} somehow got close message without CloseFrame");
|
||||
}
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
|
||||
Message::Pong(v) => {
|
||||
println!(">>> {} got pong with {:?}", who, v);
|
||||
println!(">>> {who} got pong with {v:?}");
|
||||
}
|
||||
// Just as with axum server, the underlying tungstenite websocket library
|
||||
// will handle Ping for you automagically by replying with Pong and copying the
|
||||
// v according to spec. But if you need the contents of the pings you can see them here.
|
||||
Message::Ping(v) => {
|
||||
println!(">>> {} got ping with {:?}", who, v);
|
||||
println!(">>> {who} got ping with {v:?}");
|
||||
}
|
||||
|
||||
Message::Frame(_) => {
|
||||
|
|
|
@ -101,9 +101,9 @@ async fn ws_handler(
|
|||
async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
|
||||
//send a ping (unsupported by some browsers) just to kick things off and get a response
|
||||
if socket.send(Message::Ping(vec![1, 2, 3])).await.is_ok() {
|
||||
println!("Pinged {}...", who);
|
||||
println!("Pinged {who}...");
|
||||
} else {
|
||||
println!("Could not send ping {}!", who);
|
||||
println!("Could not send ping {who}!");
|
||||
// no Error here since the only thing we can do is to close the connection.
|
||||
// If we can not send messages, there is no way to salvage the statemachine anyway.
|
||||
return;
|
||||
|
@ -168,7 +168,7 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
|
|||
})))
|
||||
.await
|
||||
{
|
||||
println!("Could not send Close due to {}, probably it is ok?", e);
|
||||
println!("Could not send Close due to {e}, probably it is ok?");
|
||||
}
|
||||
n_msg
|
||||
});
|
||||
|
@ -190,29 +190,29 @@ async fn handle_socket(mut socket: WebSocket, who: SocketAddr) {
|
|||
tokio::select! {
|
||||
rv_a = (&mut send_task) => {
|
||||
match rv_a {
|
||||
Ok(a) => println!("{} messages sent to {}", a, who),
|
||||
Err(a) => println!("Error sending messages {:?}", a)
|
||||
Ok(a) => println!("{a} messages sent to {who}"),
|
||||
Err(a) => println!("Error sending messages {a:?}")
|
||||
}
|
||||
recv_task.abort();
|
||||
},
|
||||
rv_b = (&mut recv_task) => {
|
||||
match rv_b {
|
||||
Ok(b) => println!("Received {} messages", b),
|
||||
Err(b) => println!("Error receiving messages {:?}", b)
|
||||
Ok(b) => println!("Received {b} messages"),
|
||||
Err(b) => println!("Error receiving messages {b:?}")
|
||||
}
|
||||
send_task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
// returning from the handler closes the websocket connection
|
||||
println!("Websocket context {} destroyed", who);
|
||||
println!("Websocket context {who} destroyed");
|
||||
}
|
||||
|
||||
/// helper to print contents of messages to stdout. Has special treatment for Close.
|
||||
fn process_message(msg: Message, who: SocketAddr) -> ControlFlow<(), ()> {
|
||||
match msg {
|
||||
Message::Text(t) => {
|
||||
println!(">>> {} sent str: {:?}", who, t);
|
||||
println!(">>> {who} sent str: {t:?}");
|
||||
}
|
||||
Message::Binary(d) => {
|
||||
println!(">>> {} sent {} bytes: {:?}", who, d.len(), d);
|
||||
|
@ -224,19 +224,19 @@ fn process_message(msg: Message, who: SocketAddr) -> ControlFlow<(), ()> {
|
|||
who, cf.code, cf.reason
|
||||
);
|
||||
} else {
|
||||
println!(">>> {} somehow sent close message without CloseFrame", who);
|
||||
println!(">>> {who} somehow sent close message without CloseFrame");
|
||||
}
|
||||
return ControlFlow::Break(());
|
||||
}
|
||||
|
||||
Message::Pong(v) => {
|
||||
println!(">>> {} sent pong with {:?}", who, v);
|
||||
println!(">>> {who} sent pong with {v:?}");
|
||||
}
|
||||
// You should never need to manually handle Message::Ping, as axum's websocket library
|
||||
// will do so for you automagically by replying with Pong and copying the v according to
|
||||
// spec. But if you need the contents of the pings you can see them here.
|
||||
Message::Ping(v) => {
|
||||
println!(">>> {} sent ping with {:?}", who, v);
|
||||
println!(">>> {who} sent ping with {v:?}");
|
||||
}
|
||||
}
|
||||
ControlFlow::Continue(())
|
||||
|
|
Loading…
Add table
Reference in a new issue