0
0
mirror of https://github.com/neon-mmd/websurfx.git synced 2024-10-18 06:22:53 -04:00
websurfx/src/lib.rs

64 lines
2.2 KiB
Rust
Raw Normal View History

//! This main library module provides the functionality to provide and handle the Tcp server
//! and register all the routes for the `websurfx` meta search engine website.
2023-04-22 07:35:07 -04:00
pub mod engines;
pub mod server;
pub mod search_results_handler;
2023-04-27 22:39:58 -04:00
use std::net::TcpListener;
use crate::server::routes;
use actix_files as fs;
use actix_web::{middleware::Logger, web, App, HttpServer, dev::Server};
use handlebars::Handlebars;
/// Runs the web server on the provided TCP listener and returns a `Server` instance.
///
/// # Arguments
///
/// * `listener` - A `TcpListener` instance representing the address and port to listen on.
///
/// # Returns
///
/// Returns a `Result` containing a `Server` instance on success, or an `std::io::Error` on failure.
///
/// # Example
///
/// ```rust
2023-04-27 22:39:58 -04:00
/// use std::net::TcpListener;
/// use websurfx::run;
2023-04-27 22:39:58 -04:00
///
/// let listener = TcpListener::bind("127.0.0.1:8080").expect("Failed to bind address");
/// let server = run(listener).expect("Failed to start server");
2023-04-27 22:39:58 -04:00
/// ```
pub fn run(listener: TcpListener) -> std::io::Result<Server> {
let mut handlebars: Handlebars = Handlebars::new();
handlebars
.register_templates_directory(".html", "./public/templates")
.unwrap();
let handlebars_ref: web::Data<Handlebars> = web::Data::new(handlebars);
let server = HttpServer::new(move || {
App::new()
.app_data(handlebars_ref.clone())
.wrap(Logger::default()) // added logging middleware for logging.
// Serve images and static files (css and js files).
.service(fs::Files::new("/static", "./public/static").show_files_listing())
.service(fs::Files::new("/images", "./public/images").show_files_listing())
.service(routes::robots_data) // robots.txt
.service(routes::index) // index page
.service(routes::search) // search page
.service(routes::about) // about page
.service(routes::settings) // settings page
.default_service(web::route().to(routes::not_found)) // error page
})
// Start server on 127.0.0.1 with the user provided port number. for example 127.0.0.1:8080.
.listen(listener)?
.run();
Ok(server)
}