Skip to content

Commit

Permalink
refactor(meta): use axum-embed to embed dashboard assets
Browse files Browse the repository at this point in the history
  • Loading branch information
BugenZhao committed Apr 3, 2024
1 parent 5cae694 commit 520d13b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 30 deletions.
15 changes: 15 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions src/meta/dashboard/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repository = { workspace = true }
[dependencies]
anyhow = "1"
axum = "=0.7.4" # TODO: 0.7.5+ does not work with current toolchain
axum-embed = "0.1"
bytes = "1"
hyper = "1"
mime_guess = "2"
Expand Down
33 changes: 3 additions & 30 deletions src/meta/dashboard/src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use axum::http::{header, StatusCode, Uri};
use axum::response::{IntoResponse as _, Response};
use axum::Router;
use axum_embed::ServeEmbed;
use rust_embed::RustEmbed;

#[derive(RustEmbed)]
#[derive(RustEmbed, Clone)]
#[folder = "$OUT_DIR/assets"]
struct Assets;

// TODO: switch to `axum-embed` for better robustness after bumping to axum 0.7.
async fn static_handler(uri: Uri) -> Response {
let path = {
if uri.path().ends_with('/') {
// Append `index.html` to directory paths.
format!("{}index.html", uri.path())
} else {
uri.path().to_owned()
}
};
let path = path.trim_start_matches('/');

match Assets::get(path) {
Some(file) => {
let mime = file.metadata.mimetype();

let mut res = file.data.into_response();
res.headers_mut()
.insert(header::CONTENT_TYPE, mime.parse().unwrap());
res
}

None => (StatusCode::NOT_FOUND, "Not Found").into_response(),
}
}

/// Router for embedded assets.
pub(crate) fn router() -> Router {
Router::new().fallback(static_handler)
Router::new().nest_service("/", ServeEmbed::<Assets>::new())
}

0 comments on commit 520d13b

Please sign in to comment.