Skip to content

Commit 123583c

Browse files
authored
Merge pull request #2 from intelliconnect:dev_beta
Add logging for IP address in HTTP requests to API
2 parents c1ec6df + 1673bf2 commit 123583c

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

src/main.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
use axum::{
2-
extract::Multipart,
3-
http::StatusCode,
4-
routing::{get, post},
5-
Extension, Json, Router,
2+
extract::{ConnectInfo, Multipart, Request}, http::StatusCode, middleware::Next, response::IntoResponse, routing::{get, post}, Extension, Json, Router
63
};
7-
use std::collections::HashMap;
4+
use std::{collections::HashMap, net::SocketAddr};
85
use tower_http::cors::CorsLayer;
96
use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt};
10-
117
use aws_sdk_s3 as s3;
12-
138
use s3::Client;
149

10+
async fn log_request_ip(
11+
ConnectInfo(addr): ConnectInfo<SocketAddr>,
12+
req: Request<axum::body::Body>,
13+
next: Next,
14+
) -> impl IntoResponse {
15+
// log the ip address of the request
16+
tracing::info!("Request from IP: {}", addr.ip());
17+
next.run(req).await
18+
}
19+
1520
#[tokio::main]
1621
async fn main() {
1722
// configuration for logging
@@ -30,22 +35,22 @@ async fn main() {
3035
let aws_s3_client = s3::Client::new(&aws_configuration);
3136

3237
let app = Router::new()
33-
// route for testing if api is running correctly
3438
.route("/", get(|| async move { "welcome to Image upload api" }))
35-
//route for uploading image or any file
3639
.route("/upload", post(upload_image))
37-
// set your cors config
3840
.layer(cors_layer)
39-
// pass the aws s3 client to route handler
40-
.layer(Extension(aws_s3_client));
41+
.layer(Extension(aws_s3_client))
42+
.layer(axum::middleware::from_fn(log_request_ip));
4143

4244
let addr = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
4345

4446
tracing::debug!("starting server on port: {}", addr.local_addr().unwrap().port());
4547

46-
axum::serve(addr, app)
47-
.await
48-
.expect("Failed to start server");
48+
axum::serve(
49+
addr,
50+
app.into_make_service_with_connect_info::<SocketAddr>()
51+
)
52+
.await
53+
.expect("Failed to start server");
4954
}
5055

5156
// handler to upload image or file

0 commit comments

Comments
 (0)