Skip to content

Commit

Permalink
feat: put frontend into binary
Browse files Browse the repository at this point in the history
  • Loading branch information
torfmaster committed Dec 30, 2023
1 parent 33f6b5d commit 913cc3a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ async-trait = "0.1.64"
serde_json = "1.0.107"
axum = "0.7.3"
tower-http = { version="0.5.0", features=["fs", "cors"] }
include_dir = "0.7.3"
mime_guess = "2.0.4"

[profile.release]
lto = true
34 changes: 31 additions & 3 deletions server/src/rest/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,50 @@
use std::{collections::HashMap, sync::Arc};

use axum::{
extract::{FromRef, State},
response::Html,
body::Body,
extract::{FromRef, Path, State},
http::{header, HeaderValue, StatusCode},
response::{Html, IntoResponse, Response},
routing::get,
Json, Router,
};
use chrono::{Duration, Utc};
use hackdose_server_shared::DataPoint;
use hackdose_sml_parser::application::{domain::AnyValue, obis::Obis};
use tokio::sync::Mutex;
use tokio_stream::Empty;
use tower_http::{
body::{self, Full},
cors::CorsLayer,
services::{ServeDir, ServeFile},
};

use crate::{data::EnergyData, Configuration};

use include_dir::{include_dir, Dir};

static STATIC_DIR: Dir<'_> = include_dir!("app/dist/");

async fn static_path(Path(path): Path<String>) -> Response<Body> {
let path = path.trim_start_matches('/');
let mime_type = mime_guess::from_path(path).first_or_text_plain();

match STATIC_DIR.get_file(path) {
None => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap(),
Some(file) => Response::builder()
.status(StatusCode::OK)
.header(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref()).unwrap(),
)
.body(Body::from(file.contents()))
.unwrap(),
}
}

#[derive(Clone)]
struct SmartMeterState(Arc<Mutex<HashMap<Obis, AnyValue>>>);

Expand Down Expand Up @@ -54,7 +82,7 @@ pub(crate) async fn serve_rest_endpoint(
.route("/api/data_raw", get(data_raw))
.layer(CorsLayer::permissive())
.nest_service("/api/log", ServeFile::new(config.log_location.clone()))
.nest_service("/", ServeDir::new("../app/dist"))
.route("/*path", get(static_path))
.with_state(app_state);

let _ = axum::serve(listener, app).await;
Expand Down

0 comments on commit 913cc3a

Please sign in to comment.