Skip to content

Commit

Permalink
Merge pull request #4 from hubertshelley/develop
Browse files Browse the repository at this point in the history
public 0.3.0
  • Loading branch information
hubertshelley authored May 6, 2023
2 parents b15c3b1 + 6d20749 commit e190be6
Show file tree
Hide file tree
Showing 8 changed files with 196 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/target
/Cargo.lock
.idea/
static/
11 changes: 11 additions & 0 deletions examples/file_server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "file_server"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
silent = { path = "../../silent" }
async-trait = "0.1.68"
tokio = { version = "1", features = ["full"] }
32 changes: 32 additions & 0 deletions examples/file_server/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use silent::prelude::*;
use std::sync::Arc;

fn main() {
logger::fmt().init();
if !std::path::Path::new("static").is_dir() {
std::fs::create_dir("static").unwrap();
std::fs::write(
"./static/index.html",
r#"<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Silent</title>
</head>
<body>
<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
</body>
</html>"#,
)
.unwrap();
}
let mut route = Route::new("<path:**>");
route
.get_handler_mut()
.insert(Method::GET, Arc::new(static_handler("static")));
Server::new().bind_route(route).run();
}
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Silent 是一个简单的基于Hyper的Web框架,它的目标是提供一个

- [x] 路由
- [ ] 中间件
- [ ] 静态文件
- [x] 静态文件
- [ ] 模板
- [ ] 数据库
- [x] 日志 (使用了tracing)
Expand Down
2 changes: 1 addition & 1 deletion silent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ keywords = ["web", "web-framework"]
license = "Apache-2.0"
readme = "../readme.md"
repository = "https://github.com/hubertshelley/silent"
version = "0.2.1"
version = "0.3.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Expand Down
143 changes: 143 additions & 0 deletions silent/src/handler/handler_wrapper_static.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
use crate::prelude::PathParam;
use crate::{Handler, Request, Response, SilentError, StatusCode};
use async_trait::async_trait;

struct HandlerWrapperStatic {
path: String,
}

impl Default for HandlerWrapperStatic {
fn default() -> Self {
Self::new(".")
}
}

impl HandlerWrapperStatic {
fn new(path: &str) -> Self {
let mut path = path;
if path.ends_with('/') {
path = &path[..path.len() - 1];
}
if !std::path::Path::new(path).is_dir() {
panic!("Path not exists: {}", path);
}
Self {
path: path.to_string(),
}
}
}

#[async_trait]
impl Handler for HandlerWrapperStatic {
async fn call(&self, req: Request) -> Result<Response, SilentError> {
if let PathParam::Path(file_path) = req.get_path_params("path").unwrap() {
let mut path = format!("{}/{}", self.path, file_path);
if path.ends_with('/') {
path.push_str("index.html");
}
if let Ok(contents) = tokio::fs::read(path).await {
return Ok(contents.into());
}
};
Err(SilentError::BusinessError {
code: StatusCode::NOT_FOUND,
msg: "Not Found".to_string(),
})
}
}

pub fn static_handler(path: &str) -> impl Handler {
HandlerWrapperStatic::new(path)
}

#[cfg(test)]
mod tests {
use super::HandlerWrapperStatic;
use crate::prelude::*;
use crate::Handler;
use crate::Request;
use crate::SilentError;
use crate::StatusCode;
use bytes::Bytes;
use http_body_util::BodyExt;

static CONTENT: &str = r#"<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Silent</title>
</head>
<body>
<h1>我的第一个标题</h1>
<p>我的第一个段落。</p>
</body>
</html>"#;

fn create_static(path: &str) {
if !std::path::Path::new(path).is_dir() {
std::fs::create_dir(path).unwrap();
std::fs::write(format!("./{}/index.html", path), CONTENT).unwrap();
}
}

fn clean_static(path: &str) {
if std::path::Path::new(path).is_dir() {
std::fs::remove_file(format!("./{}/index.html", path)).unwrap();
std::fs::remove_dir(path).unwrap();
}
}

#[tokio::test]
async fn test_static() {
let path = "test_static";
create_static(path);
let handler = HandlerWrapperStatic::new(path);
let mut req = Request::default();
req.set_path_params("path".to_owned(), PathParam::Path("index.html".to_string()));
let mut res = handler.call(req).await.unwrap();
clean_static(path);
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(
res.frame().await.unwrap().unwrap().data_ref().unwrap(),
&Bytes::from(CONTENT)
);
}

#[tokio::test]
async fn test_static_default() {
let path = "test_static_default";
create_static(path);
let handler = HandlerWrapperStatic::new(path);
let mut req = Request::default();
req.set_path_params("path".to_owned(), PathParam::Path("".to_string()));
let mut res = handler.call(req).await.unwrap();
clean_static(path);
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(
res.frame().await.unwrap().unwrap().data_ref().unwrap(),
&Bytes::from(CONTENT)
);
}

#[tokio::test]
async fn test_static_not_found() {
let path = "test_static_not_found";
create_static(path);
let handler = HandlerWrapperStatic::new(path);
let mut req = Request::default();
req.set_path_params(
"path".to_owned(),
PathParam::Path("not_found.html".to_string()),
);
let res = handler.call(req).await.unwrap_err();
clean_static(path);
if let SilentError::BusinessError { code, .. } = res {
assert_eq!(code, StatusCode::NOT_FOUND);
} else {
panic!();
}
}
}
2 changes: 2 additions & 0 deletions silent/src/handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
mod handler_trait;
mod handler_wrapper;
mod handler_wrapper_html;
mod handler_wrapper_static;

pub use handler_trait::Handler;
pub(crate) use handler_wrapper::HandlerWrapper;
pub(crate) use handler_wrapper_html::HandlerWrapperHtml;
pub use handler_wrapper_static::static_handler;
8 changes: 5 additions & 3 deletions silent/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ pub(crate) use handler::HandlerWrapper;
pub use hyper::{header, Method, StatusCode};

pub mod prelude {
pub use crate::core::{path_param::PathParam, request::Request, response::Response};
pub use crate::core::{
path_param::PathParam, request::Request, res_body::full, response::Response,
};
pub use crate::error::SilentError;
pub use crate::handler::Handler;
pub use crate::handler::{static_handler, Handler};
pub use crate::log::{logger, Level};
pub use crate::route::handler_append::{HandlerAppend, HtmlHandlerAppend};
pub use crate::route::handler_append::{HandlerAppend, HandlerGetter, HtmlHandlerAppend};
pub use crate::route::Route;
pub use crate::service::Server;
pub use hyper::{header, Method, StatusCode};
Expand Down

0 comments on commit e190be6

Please sign in to comment.