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

#enviroment variables
.env
.env

# MacOs Finder files
.DS_Store
._*

9 changes: 6 additions & 3 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 Expand Up @@ -168,7 +169,9 @@ async fn main() {
The project integrates Swagger for API documentation using OpenAPI. This allows for automatically generated and interactive API documentation, making it easier for developers to understand and interact with the API endpoints.

#### Enabling Swagger
To enable Swagger documentation in the project, ensure that the necessary dependencies are included and configured to generate the OpenAPI specification, which can then be served and viewed using tools like Swagger UI.
To enable Swagger documentation in the project, ensure that the necessary dependencies are included and configured to generate the OpenAPI specification, which can then be served and viewed using tools like Swagger UI.

The `utoipa-swagger-ui` crate downloads the Swagger UI assets at build time. Ensure network access is available, or provide an alternate archive URL via the `SWAGGER_UI_DOWNLOAD_URL` environment variable before running `cargo build` or `cargo test`.

## Getting Started

Expand Down
Binary file added public/image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rust Base Backend</title>
</head>
<body>
<h1>Static file served</h1>
<img src="/image.jpg" alt="Logo" style="width: 200px; height: auto;">
<p>Welcome to the Rust Base Backend static file server!</p>
<p>This page is served from the <code>public/index.html</code> file.</p>
<p>Check the <code>.gitignore</code> file for ignored files in this project.</p>
<p>Enjoy your stay!</p>
<footer>
<p>&copy; 2023 Rust Base Backend</p>
<img src="/image.png" alt="Logo" style="width: 50px; height: auto;">
<p>Powered by Rust</p>
</footer>
</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
139 changes: 73 additions & 66 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,73 @@

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::errors;
use crate::swagger;
use crate::swagger::serve_swagger;
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 18, 2025

Choose a reason for hiding this comment

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

The closure is unnecessarily complex. Since warp::reply::json() already returns a valid reply, you can simplify this to .map(|| warp::reply::json(&swagger::ApiDoc::openapi()))

Suggested change
.and_then(|| async { Ok::<_, Rejection>(warp::reply::json(&swagger::ApiDoc::openapi())) });
.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 (addr, 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 {}", addr.port());
println!("API base path: /{}", config.api_base);

(tx, format!("http://127.0.0.1:{}", addr.port()))
}
Binary file added src/swagger-ui.zip
Binary file not shown.
Loading