1
1
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
6
3
} ;
7
- use std:: collections:: HashMap ;
4
+ use std:: { collections:: HashMap , net :: SocketAddr } ;
8
5
use tower_http:: cors:: CorsLayer ;
9
6
use tracing_subscriber:: { prelude:: __tracing_subscriber_SubscriberExt, util:: SubscriberInitExt } ;
10
-
11
7
use aws_sdk_s3 as s3;
12
-
13
8
use s3:: Client ;
14
9
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
+
15
20
#[ tokio:: main]
16
21
async fn main ( ) {
17
22
// configuration for logging
@@ -30,22 +35,22 @@ async fn main() {
30
35
let aws_s3_client = s3:: Client :: new ( & aws_configuration) ;
31
36
32
37
let app = Router :: new ( )
33
- // route for testing if api is running correctly
34
38
. route ( "/" , get ( || async move { "welcome to Image upload api" } ) )
35
- //route for uploading image or any file
36
39
. route ( "/upload" , post ( upload_image) )
37
- // set your cors config
38
40
. 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 ) ) ;
41
43
42
44
let addr = tokio:: net:: TcpListener :: bind ( "0.0.0.0:3000" ) . await . unwrap ( ) ;
43
45
44
46
tracing:: debug!( "starting server on port: {}" , addr. local_addr( ) . unwrap( ) . port( ) ) ;
45
47
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" ) ;
49
54
}
50
55
51
56
// handler to upload image or file
0 commit comments