Skip to content
Closed
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ Cargo.lock
/target

#enviroment variables
.env
.env
# swagger ui
swagger-ui.zip
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ Rust-Base-Backend is a foundational backend project written in Rust, designed wi

## Features
- Modular and scalable architecture
- RESTful API setup
- Docker support for containerization
- RESTful API setup
- Static file serving from the `public` directory
- Docker support for containerization
- Middleware for parameter validation
- Error handling conforming to RFC 7807
- Asynchronous programming with Tokio
Expand Down
10 changes: 10 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rust Base Backend</title>
</head>
<body>
<h1>Static file served</h1>
</body>
</html>
25 changes: 14 additions & 11 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
use std::env;

pub struct Config {
pub port: u16,
pub api_base: String
pub port: u16,
pub api_base: String,
pub static_dir: String,
}

impl Config {
pub fn from_env() -> Self {
Self {
port: env::var("PORT")
.unwrap_or_else(|_| "3030".to_string())
.parse()
.expect("PORT must be a number"),
api_base : env::var("API_BASE").unwrap_or_else(|_| "/api/v1".trim_matches('/').to_string())
pub fn from_env() -> Self {
Self {
port: env::var("PORT")
.unwrap_or_else(|_| "3030".to_string())
.parse()
.expect("PORT must be a number"),
api_base: env::var("API_BASE")
.unwrap_or_else(|_| "/api/v1".trim_matches('/').to_string()),
static_dir: env::var("STATIC_DIR").unwrap_or_else(|_| "public".to_string()),
}
}
}
}
}
4 changes: 2 additions & 2 deletions src/controllers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod base_controller;

use std::convert::Infallible;
use warp::Rejection;
use std::sync::Arc;

use crate::repositories::base_Repository::InMemoryBaseRepository;
Expand All @@ -9,7 +9,7 @@ use crate::config::Config;
use crate::router::Router;


pub fn base_routes(config: Arc<Config>) -> impl warp::Filter<Extract = impl warp::Reply, Error = Infallible> +Clone {
pub fn base_routes(config: Arc<Config>) -> impl warp::Filter<Extract = impl warp::Reply, Error = Rejection> +Clone {
let repository = InMemoryBaseRepository::new();
let service = BaseServiceImpl::new(repository);
let router = Router::new(service, Arc::clone(&config));
Expand Down
12 changes: 6 additions & 6 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use warp::Filter;
use crate::services::base_service::BaseService;
use crate::config::Config;
use std::sync::Arc;
use std::convert::Infallible;
use std::convert::Infallible;
use warp::Rejection;
use crate::controllers::base_controller::{handle_get_messages, handle_create_message, handle_search_messages};

pub struct Router<S: BaseService> {
Expand All @@ -19,7 +20,7 @@ impl<S: BaseService + Send + Sync + 'static> Router<S> {
}


pub fn routes(&self) -> impl Filter<Extract = impl warp::Reply, Error = Infallible> + Clone {
pub fn routes(&self) -> impl Filter<Extract = impl warp::Reply, Error = Rejection> + Clone {
let service = self.service.clone();
let api_base = self.config.api_base.trim_matches('/').to_string();
let api_segments: Vec<String> = api_base.split('/').map(|s| s.to_string()).collect();
Expand Down Expand Up @@ -52,10 +53,9 @@ pub fn routes(&self) -> impl Filter<Extract = impl warp::Reply, Error = Infallib
.and(with_service(Arc::clone(&service)))
.and_then(handle_search_messages);

get_messages
.or(add_message)
.or(search_messages)
.recover(crate::errors::handle_rejection)
get_messages
.or(add_message)
.or(search_messages)
}
}

Expand Down
141 changes: 75 additions & 66 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,75 @@

use dotenv::dotenv;
use std::sync::Arc;
use crate::swagger::serve_swagger;
use tokio::sync::oneshot;
use crate::config;
use crate::controllers;
use crate::swagger;


use utoipa::{
openapi::security::{ApiKey, ApiKeyValue, SecurityScheme},
Modify, OpenApi, openapi::Server
};
use utoipa_swagger_ui::Config;
use warp::{
http::Uri,
hyper::{Response, StatusCode},
path::{FullPath, Tail},
Filter, Rejection, Reply,
};

pub async fn run_server() -> (oneshot::Sender<()>, String) {
dotenv().ok();

let config = Arc::new(config::Config::from_env());
let config_swagger = Arc::new(Config::from(format!("/{}/api-doc.json", config.api_base)));
let routes = controllers::base_routes(Arc::clone(&config));

let port:u16 = config.port;
let api_base = config.api_base.trim_matches('/').to_string();
let api_segments: Vec<String> = api_base.split('/').map(|s| s.to_string()).collect();

let mut api_path = warp::path(api_segments[0].clone()).boxed();
for segment in &api_segments[1..] {
api_path = api_path.and(warp::path(segment.clone())).boxed();
}

let api_doc = api_path.clone()
.and(warp::path("api-doc.json"))
.and(warp::get())
.map(|| warp::reply::json(&swagger::ApiDoc::openapi()));

let swagger_ui = api_path.clone()
.and(warp::path("swagger-ui"))
.and(warp::get())
.and(warp::path::full())
.and(warp::path::tail())
.and(warp::any().map(move || config_swagger.clone()))
.and_then(serve_swagger);

let (tx, rx) = oneshot::channel();
let routes = api_doc.or(swagger_ui).or(routes);

let (_, server) = warp::serve(routes)
.bind_with_graceful_shutdown(([127,0,0,1], port), async {
rx.await.ok();
});

tokio::spawn(server);

println!("Server starting on port {}", port);
println!("API base path: /{}", config.api_base);

(tx, format!("http://127.0.0.1:{}", port))
}
use crate::config;
use crate::controllers;
use crate::swagger;
use crate::swagger::serve_swagger;
use crate::errors;
use dotenv::dotenv;
use std::sync::Arc;
use tokio::sync::oneshot;

use utoipa::{
openapi::security::{ApiKey, ApiKeyValue, SecurityScheme},
openapi::Server,
Modify, OpenApi,
};
use utoipa_swagger_ui::Config;
use warp::{
http::Uri,
hyper::{Response, StatusCode},
path::{FullPath, Tail},
Filter, Rejection, Reply,
};

pub async fn run_server() -> (oneshot::Sender<()>, String) {
dotenv().ok();

let config = Arc::new(config::Config::from_env());
let config_swagger = Arc::new(Config::from(format!("/{}/api-doc.json", config.api_base)));
let routes = controllers::base_routes(Arc::clone(&config));
let static_files = warp::fs::dir(config.static_dir.clone());

let port: u16 = config.port;
let api_base = config.api_base.trim_matches('/').to_string();
let api_segments: Vec<String> = api_base.split('/').map(|s| s.to_string()).collect();

let mut api_path = warp::path(api_segments[0].clone()).boxed();
for segment in &api_segments[1..] {
api_path = api_path.and(warp::path(segment.clone())).boxed();
}

let api_doc = api_path
.clone()
.and(warp::path("api-doc.json"))
.and(warp::get())
.and_then(|| async {
Ok::<_, Rejection>(warp::reply::json(&swagger::ApiDoc::openapi()))
});
Copy link

Copilot AI Aug 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The closure should be simplified to use warp::reply::json directly without the unnecessary async block and Result wrapping.

Suggested change
});
.map(|| warp::reply::json(&swagger::ApiDoc::openapi()));

Copilot uses AI. Check for mistakes.

let swagger_ui = api_path
.clone()
.and(warp::path("swagger-ui"))
.and(warp::get())
.and(warp::path::full())
.and(warp::path::tail())
.and(warp::any().map(move || config_swagger.clone()))
.and_then(serve_swagger);

let (tx, rx) = oneshot::channel();
let routes = api_doc
.or(swagger_ui)
.or(routes)
.or(static_files)
.recover(errors::handle_rejection);

let (_, server) =
warp::serve(routes).bind_with_graceful_shutdown(([127, 0, 0, 1], port), async {
rx.await.ok();
});

tokio::spawn(server);

println!("Server starting on port {}", port);
println!("API base path: /{}", config.api_base);

(tx, format!("http://127.0.0.1:{}", port))
}
Loading
Loading