11use 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 } ;
85use tower_http:: cors:: CorsLayer ;
96use tracing_subscriber:: { prelude:: __tracing_subscriber_SubscriberExt, util:: SubscriberInitExt } ;
10-
117use aws_sdk_s3 as s3;
12-
138use 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]
1621async 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