1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
use hiccup::{SimUpdates, Simulation};
use serde::Deserialize;
use std::fs;
use axum::{
http::header::CONTENT_TYPE,
response::{Html, Json, IntoResponse},
routing::{get, post},
Router,
};
async fn root_get() -> Html<String> {
let head = "
<head>
<meta charset=\"UTF-8\">
<title>Hiccup</title>
<link href=\"/main.css\" rel=\"stylesheet\">
<script src=\"/main.js\"></script>
</head>
";
let body = "
<body>
<div id=\"main\"></div>
<script>
var app = Elm.Main.init({
node: document.getElementById('main')
});
</script>
</body>
";
Html(format!("<!DOCTYPE html>{head}{body}"))
}
async fn main_js_get() -> impl IntoResponse {
([(CONTENT_TYPE, "text/javascript")], fs::read_to_string("front/main.js").unwrap())
}
async fn main_css_get() -> impl IntoResponse {
([(CONTENT_TYPE, "text/css")], fs::read_to_string("front/main.css").unwrap())
}
#[derive(Deserialize)]
struct SimSpecs {
principal: f64,
i1: f64,
years: u32,
updates: SimUpdates
}
async fn api_simulate_post(Json(specs): Json<SimSpecs>) -> Json<hiccup::Simulation> {
let mut sim = Simulation::new(specs.principal, specs.i1, specs.years);
let updates: SimUpdates = specs.updates;
sim.run(updates);
Json(sim)
}
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new()
.route("/", get(root_get))
.route("/main.js", get(main_js_get))
.route("/main.css", get(main_css_get))
.route("/api/simulate", post(api_simulate_post));
// 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();
}
|