Skip to content

Commit

Permalink
add Static embed example (#102)
Browse files Browse the repository at this point in the history
* add static-embed

* embed

* Revert "embed"

This reverts commit 15ad319.

* move
  • Loading branch information
Baiyuetribe authored Dec 1, 2023
1 parent 3d1e46d commit 556f667
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ members = [
"examples/unix-socket",
"examples/static-files/embed",
"examples/static-files/serve",
"examples/static-files/static-embed",
"examples/limits",
"examples/forms/form",
"examples/forms/multipart",
Expand Down Expand Up @@ -40,7 +41,7 @@ homepage = "https://viz.rs"
documentation = "https://docs.rs/viz"
repository = "https://github.com/viz-rs/viz"
license = "MIT"
rust-version = "1.63" # follows `tokio` and `hyper`
rust-version = "1.63" # follows `tokio` and `hyper`

[workspace.dependencies]
viz = { version = "0.5.0-rc.2", path = "viz" }
Expand Down
12 changes: 12 additions & 0 deletions examples/static-files/static-embed/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "static-embed"
version = "0.1.0"
edition.workspace = true
publish = false

[dependencies]
viz.workspace = true
include_dir = "0.7.3"
http-body-util = "0.1"

tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
3 changes: 3 additions & 0 deletions examples/static-files/static-embed/html/assets/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h2 {
color: red;
}
13 changes: 13 additions & 0 deletions examples/static-files/static-embed/html/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="assets/style.css" />
</head>
<body>
<h2>hello word!</h2>
<h3>hello word!</h3>
</body>
</html>
55 changes: 55 additions & 0 deletions examples/static-files/static-embed/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#![deny(warnings)]
#![allow(clippy::unused_async)]

use http_body_util::Full;
use include_dir::{include_dir, Dir};
use std::{net::SocketAddr, sync::Arc};
use tokio::net::TcpListener;
use viz::{
serve, IntoResponse, Request, RequestExt, Response, ResponseExt, Result, Router, StatusCode,
Tree,
};

const ASSETS: Dir = include_dir!("examples/static-files/static-embed/html"); // frontend dir

pub async fn index(_: Request) -> Result<Response> {
let file_content = ASSETS
.get_file("index.html")
.unwrap()
.contents_utf8()
.unwrap();
Ok(Response::html(file_content))
}

pub async fn assets(req: Request) -> Result<Response> {
let path = req.path().trim_start_matches('/');
if path.contains("..") {
return Ok(StatusCode::FORBIDDEN.into_response());
}
Ok(match ASSETS.get_file(path) {
Some(v) => {
let data = v.contents();
Response::builder().body(Full::from(data).into())?
}
None => StatusCode::NOT_FOUND.into_response(),
})
}

#[tokio::main]
async fn main() -> Result<()> {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = TcpListener::bind(addr).await?;
println!("listening on http://{addr}");

let app = Router::new()
.any("/*", |_| async { Ok(StatusCode::NOT_FOUND) })
.get("/", index)
.get("/*", assets);
let tree = Arc::new(Tree::from(app));

loop {
let (stream, addr) = listener.accept().await?;
let tree = tree.clone();
tokio::task::spawn(serve(stream, tree, Some(addr)));
}
}

0 comments on commit 556f667

Please sign in to comment.