feat: add api functions and actix webserver

This commit is contained in:
Alex Wellnitz 2024-02-12 21:45:27 +01:00
parent af7140790c
commit c502f1da49
10 changed files with 87 additions and 38 deletions

View File

@ -1,3 +0,0 @@
pub async fn say_hello() -> &'static str {
"Hello, World!"
}

View File

@ -1,17 +0,0 @@
use axum::
Json
;
use serde::Deserialize;
use crate::search::engine::SearchEngine;
pub fn index_new_document(mut engine: SearchEngine, Json(payload): Json<IndexNewDocument>) {
engine.index(&payload.url, &payload.content);
}
// the input to our `create_user` handler
#[derive(Deserialize)]
pub struct IndexNewDocument {
url: String,
content: String,
}

15
src/handlers/hello.rs Normal file
View File

@ -0,0 +1,15 @@
use actix_web::{get, post, HttpResponse, Responder};
#[get("/")]
pub async fn say_hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/echo")]
pub async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
pub async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
}

2
src/handlers/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod hello;
pub mod search;

20
src/handlers/search.rs Normal file
View File

@ -0,0 +1,20 @@
use actix_web::{web, HttpResponse, Responder};
use serde::Deserialize;
use crate::types::app_state::AppStateWithSearchEngine;
#[derive(Deserialize)]
pub struct AddDocumentRequest {
url: String,
content: String,
}
pub async fn add_document_to_index(data: web::Data<AppStateWithSearchEngine>, req: web::Json<AddDocumentRequest>) -> impl Responder {
data.search_engine.lock().unwrap().index(&req.url, &req.content);
HttpResponse::Created().body("Document added to index!")
}
pub async fn get_number_of_documents(data: web::Data<AppStateWithSearchEngine>) -> impl Responder {
let number_of_documents = data.search_engine.lock().unwrap().number_of_documents();
HttpResponse::Ok().body(format!("Number of documents: {}", number_of_documents))
}

View File

@ -1,2 +1,3 @@
pub mod search;
pub mod handler;
pub mod handlers;
pub mod types;

View File

@ -1,23 +1,45 @@
use axum::{routing::get, Router};
use std::sync::Mutex;
use rustysearch::search::engine::SearchEngine;
use actix_web::{middleware::Logger, web, App, HttpServer};
use env_logger::Env;
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
use rustysearch::{
handlers::{hello, search},
search::engine::SearchEngine,
types::app_state::AppStateWithSearchEngine,
};
// initialize our search engine
let mut search_engine = SearchEngine::new(1.5, 0.75);
search_engine.index("https://www.rust-lang.org/", "Rust Programming Language");
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Initialize logger
env_logger::init_from_env(Env::default().default_filter_or("debug"));
// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.route("/", get(rustysearch::handler::hello::say_hello));
// .route("/search/add", post(rustysearch::handler::search::index_new_document));
let search_engine = SearchEngine::new(1.5, 0.75);
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
let app_state = web::Data::new(AppStateWithSearchEngine {
search_engine: Mutex::new(search_engine.clone()),
});
HttpServer::new(move || {
App::new()
// Inject the search engine into the application state
.app_data(app_state.clone())
// enable logger
.wrap(Logger::default())
.service(hello::say_hello)
.service(hello::echo)
.route("/hey", web::get().to(hello::manual_hello))
// Search Routes
.route(
"/search/index/document",
web::post().to(search::add_document_to_index),
)
.route(
"/search/index/number_of_documents",
web::get().to(search::get_number_of_documents),
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

View File

@ -13,6 +13,7 @@ pub fn normalize_string(input_string: &str) -> String {
string_without_double_spaces.to_lowercase()
}
#[derive(Default, Debug, Clone)]
pub struct SearchEngine {
index: HashMap<String, HashMap<String, i32>>,
documents: HashMap<String, String>,

7
src/types/app_state.rs Normal file
View File

@ -0,0 +1,7 @@
use std::sync::Mutex;
use crate::search::engine::SearchEngine;
pub struct AppStateWithSearchEngine {
pub search_engine: Mutex<SearchEngine>, // <- Mutex is necessary to mutate safely across threads
}

1
src/types/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod app_state;