initial http server

This commit is contained in:
2024-10-19 18:22:04 -07:00
parent c9bf33ab6c
commit 4d5b525288
5 changed files with 997 additions and 100 deletions

54
server/src/http.rs Normal file
View File

@@ -0,0 +1,54 @@
use crate::TelemetryDefinition;
use actix_web::http::header::ContentType;
use actix_web::http::StatusCode;
use actix_web::{error, get, web, App, HttpResponse, HttpServer, Responder};
use derive_more::{Display, Error};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Debug, Display, Error)]
enum UserError {
#[display("Telemetry Not Found: {tlm}")]
TlmNotFound { tlm: String },
}
impl error::ResponseError for UserError {
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code())
.insert_header(ContentType::html())
.body(self.to_string())
}
fn status_code(&self) -> StatusCode {
match *self {
UserError::TlmNotFound { .. } => StatusCode::NOT_FOUND,
}
}
}
#[get("/tlm/{name:[\\w\\d/_-]+}")]
async fn get_tlm_definition(data: web::Data<Arc<Mutex<HashMap<String, TelemetryDefinition>>>>, name: web::Path<String>) -> Result<impl Responder, UserError> {
let string = name.to_string();
let data = data.lock().await;
let tlm_def = data.get(&string);
if let Some(tlm_def) = tlm_def {
Ok(web::Json(tlm_def.clone()))
} else {
Err(UserError::TlmNotFound { tlm: string })
}
}
pub async fn setup(telemetry_definitions: Arc<Mutex<HashMap<String, TelemetryDefinition>>>) -> Result<(), Box<dyn Error>> {
let data = web::Data::new(telemetry_definitions);
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.service(get_tlm_definition)
})
.bind("localhost:8080")?
.run().await?;
Ok(())
}