diff --git a/src/main.rs b/src/main.rs index fc7c869..aae6616 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,17 @@ use axum::{ + extract::{ + State, + Path, + }, + response::Html, routing::get, Router, }; use serde::Deserialize; +use std::collections::HashMap; + #[derive(Deserialize)] struct Train { name: String, @@ -39,8 +46,43 @@ struct Departures { departures: Vec, } +#[derive(Clone)] +struct Station { + name: String, + code: String, +} + +#[derive(Clone)] +struct AppState { + stations: HashMap, +} + + #[tokio::main] async fn main() { + let stations = HashMap::from([ + (String::from("berlin-hbf"), Station { + name: String::from("Berlin Hbf"), + code: String::from(""), + }), + (String::from("berlin-ostbahnhof"), Station { + name: String::from("Berlin Ostbahnhof"), + code: String::from(""), + }), + (String::from("berlin-spandau"), Station { + name: String::from("Berlin Spandau"), + code: String::from(""), + }), + (String::from("berlin-suedkreuz"), Station { + name: String::from("Berlin Südkreuz"), + code: String::from(""), + }), + (String::from("berlin-gesundbrunnen"), Station { + name: String::from("Berlin Gesundbrunnen"), + code: String::from(""), + }), + ]); + let mut args = std::env::args(); let _name = args.next().unwrap(); @@ -65,8 +107,15 @@ async fn main() { } } + let state = AppState { + stations, + }; + let app = Router::new() - .route("/station/berlin-ostbahnhof/to/berlin-hbf", get(route_station)); + .route("/", get(route_index)) + .route("/station/:station", get(route_station_overview)) + .route("/station/berlin-ostbahnhof/to/berlin-hbf", get(route_station)) + .with_state(state); let listener = tokio::net::TcpListener::bind(listen).await.unwrap(); println!("Server listening on: http://{}", listener.local_addr().unwrap()); @@ -74,6 +123,43 @@ async fn main() { axum::serve(listener, app).await.unwrap(); } +async fn route_index( + State(state): State, +) -> Result, String> { + let mut out = String::new(); + + out.push_str("
    \n"); + + for (id, station) in state.stations.into_iter() { + out.push_str(&format!("
  • {}
  • \n", id, station.name)); + } + + out.push_str("
\n"); + + return Ok(Html(out)); +} + +async fn route_station_overview( + State(state): State, + Path(station): Path +) -> Result, String> { + if !state.stations.contains_key(&station) { + return Err(String::from("")); + } + + let mut out = String::new(); + + out.push_str("
    \n"); + + for (dest_station_id, dest_station) in state.stations.into_iter() { + out.push_str(&format!("
  • {}
  • \n", station, dest_station_id, dest_station.name)); + } + + out.push_str("
      \n"); + + return Ok(Html(out)); +} + async fn route_station() -> Result { let client = reqwest::Client::new(); let stationdata_req = client.get(String::from("https://bahn.expert/api/iris/v2/abfahrten/8010255?lookahead=150&lookbehind=10"))