Skip to content

Add logging for IP address in HTTP requests to API #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
use axum::{
extract::Multipart,
http::StatusCode,
routing::{get, post},
Extension, Json, Router,
extract::{ConnectInfo, Multipart, Request}, http::StatusCode, middleware::Next, response::IntoResponse, routing::{get, post}, Extension, Json, Router
};
use std::collections::HashMap;
use std::{collections::HashMap, net::SocketAddr};
use tower_http::cors::CorsLayer;
use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt};

use aws_sdk_s3 as s3;

use s3::Client;

async fn log_request_ip(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
req: Request<axum::body::Body>,
next: Next,
) -> impl IntoResponse {
// log the ip address of the request
tracing::info!("Request from IP: {}", addr.ip());
next.run(req).await
}

#[tokio::main]
async fn main() {
// configuration for logging
Expand All @@ -30,22 +35,22 @@ async fn main() {
let aws_s3_client = s3::Client::new(&aws_configuration);

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

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

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

axum::serve(addr, app)
.await
.expect("Failed to start server");
axum::serve(
addr,
app.into_make_service_with_connect_info::<SocketAddr>()
)
.await
.expect("Failed to start server");
}

// handler to upload image or file
Expand Down