Skip to content

Commit

Permalink
Merge pull request #213 from hongquan/feature/shorter-axum
Browse files Browse the repository at this point in the history
Shorter example code for axum
  • Loading branch information
Peter John committed Jul 14, 2023
2 parents 494d979 + 2c88c43 commit a1f5565
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 14 deletions.
14 changes: 4 additions & 10 deletions examples/axum-spa/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use axum::{
body::{boxed, Full},
http::{header, StatusCode, Uri},
response::{IntoResponse, Response},
response::{Html, IntoResponse, Response},
routing::Router,
};
use rust_embed::RustEmbed;
Expand Down Expand Up @@ -31,10 +30,9 @@ async fn static_handler(uri: Uri) -> impl IntoResponse {

match Assets::get(path) {
Some(content) => {
let body = boxed(Full::from(content.data));
let mime = mime_guess::from_path(path).first_or_octet_stream();

Response::builder().header(header::CONTENT_TYPE, mime.as_ref()).body(body).unwrap()
([(header::CONTENT_TYPE, mime.as_ref())], content.data).into_response()
}
None => {
if path.contains('.') {
Expand All @@ -48,15 +46,11 @@ async fn static_handler(uri: Uri) -> impl IntoResponse {

async fn index_html() -> Response {
match Assets::get(INDEX_HTML) {
Some(content) => {
let body = boxed(Full::from(content.data));

Response::builder().header(header::CONTENT_TYPE, "text/html").body(body).unwrap()
}
Some(content) => Html(content.data).into_response(),
None => not_found().await,
}
}

async fn not_found() -> Response {
Response::builder().status(StatusCode::NOT_FOUND).body(boxed(Full::from("404"))).unwrap()
(StatusCode::NOT_FOUND, "404").into_response()
}
6 changes: 2 additions & 4 deletions examples/axum.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use axum::{
body::{boxed, Full},
http::{header, StatusCode, Uri},
response::{Html, IntoResponse, Response},
routing::{get, Router},
Expand Down Expand Up @@ -61,11 +60,10 @@ where

match Asset::get(path.as_str()) {
Some(content) => {
let body = boxed(Full::from(content.data));
let mime = mime_guess::from_path(path).first_or_octet_stream();
Response::builder().header(header::CONTENT_TYPE, mime.as_ref()).body(body).unwrap()
([(header::CONTENT_TYPE, mime.as_ref())], content.data).into_response()
}
None => Response::builder().status(StatusCode::NOT_FOUND).body(boxed(Full::from("404"))).unwrap(),
None => (StatusCode::NOT_FOUND, "404 Not Found").into_response(),
}
}
}

0 comments on commit a1f5565

Please sign in to comment.