Skip to content

Commit

Permalink
Merge pull request #2 from hubertshelley/develop
Browse files Browse the repository at this point in the history
路由已完成
  • Loading branch information
hubertshelley authored May 3, 2023
2 parents ba792f3 + f51eeff commit 20a5d4f
Show file tree
Hide file tree
Showing 52 changed files with 1,165 additions and 43 deletions.
Binary file added .DS_Store
Binary file not shown.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ repos:
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace
- repo: https://gitee.com/hubert22/black
rev: 22.10.0
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/crate-ci/typos
Expand Down
21 changes: 3 additions & 18 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,18 +1,3 @@
[package]
name = "silent"
edition = "2021"
authors = ["Hubert Shelley <[email protected]>"]
categories = ["web-programming::web", "web-programming::web-framework"]
documentation = "https://docs.rs/"
description = """
Silent Web Framework
"""
homepage = "https://github.com/hubertshelley/silent"
keywords = ["web", "web-framework"]
license = "Apache-2.0"
readme = "./readme.md"
repository = "https://github.com/hubertshelley/silent"
version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
[workspace]
members = ["silent", "examples/*"]
default-members = ["silent", ]
12 changes: 6 additions & 6 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ targets = [
db-path = "~/.cargo/advisory-db"
# The url(s) of the advisory databases to use
# db-urls = ["https://github.com/rustsec/advisory-db"]
db-urls = ["https://gitee.com/mirrors_RustSec/advisory-db"]
db-urls = ["https://github.com/rustsec/advisory-db"]
# The lint level for security vulnerabilities
vulnerability = "deny"
# The lint level for unmaintained crates
Expand Down Expand Up @@ -73,11 +73,11 @@ unlicensed = "allow"
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"ISC",
# "Apache-2.0 WITH LLVM-exception",
# "ISC",
"Unicode-DFS-2016",
"BSD-3-Clause",
"BSD-2-Clause",
# "BSD-3-Clause",
# "BSD-2-Clause",
]
# List of explicitly disallowed licenses
# See https://spdx.org/licenses/ for list of possible licenses
Expand Down Expand Up @@ -196,7 +196,7 @@ unknown-git = "warn"
# List of URLs for allowed crate registries. Defaults to the crates.io index
# if not specified. If it is specified but empty, no registries are allowed.
allow-registry = [
# "https://github.com/rust-lang/crates.io-index",
"https://github.com/rust-lang/crates.io-index",
"https://mirrors.ustc.edu.cn/crates.io-index",
]
# List of URLs for allowed Git repositories
Expand Down
7 changes: 7 additions & 0 deletions examples/hello-world/Cargo.lock

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

9 changes: 9 additions & 0 deletions examples/hello-world/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "example-hello-world"
version = "0.1.0"
edition = "2021"

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

[dependencies]
silent = { version = "0.1.0", path = "../../silent" }
7 changes: 7 additions & 0 deletions examples/hello-world/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use silent::prelude::*;

fn main() {
logger::fmt().with_max_level(Level::INFO).init();
let route = Route::new("").get(|_req| async { Ok("hello world") });
Server::new().bind_route(route).run();
}
9 changes: 9 additions & 0 deletions examples/path_params/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "path_params"
version = "0.1.0"
edition = "2021"

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

[dependencies]
silent = { version = "0.1.0", path = "../../silent" }
29 changes: 29 additions & 0 deletions examples/path_params/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use silent::prelude::*;

fn main() {
logger::fmt().with_max_level(Level::INFO).init();
// 定义路由
let route = Route::new("path_params")
.append(Route::new("<key:str>/str").get(hello_world))
.append(Route::new("<key:int>/int").get(hello_world))
.append(Route::new("<key:uuid>/uuid").get(hello_world))
.append(Route::new("<key:path>/path").get(hello_world))
.append(Route::new("<key:full_path>/full_path").get(hello_world))
.append(Route::new("<key:*>/*").get(hello_world))
.append(Route::new("<key:**>/**").get(hello_world))
.append(Route::new("<key>").get(hello_world))
.append(Route::new("<key:other>/other").get(hello_world));
println!("{:?}", route);
Server::new().bind_route(route).run();
}

// 定义处理方法
async fn hello_world(req: Request) -> Result<String, SilentError> {
let path_params = req.get_path_params("key").unwrap();
match path_params {
PathParam::String(str) => Ok(format!("str {}", str)),
PathParam::Int(int) => Ok(format!("int {}", int)),
PathParam::UUid(uuid) => Ok(format!("uuid {}", uuid)),
PathParam::Path(path) => Ok(format!("path {}", path)),
}
}
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ Silent 是一个简单的基于Hyper的Web框架,它的目标是提供一个

### 目标

- [ ] 路由
- [x] 路由
- [ ] 中间件
- [ ] 静态文件
- [ ] 模板
- [ ] 数据库
- [ ] 日志
- [x] 日志 (使用了tracing)
- [ ] 配置
- [ ] 会话
- [ ] 安全
Expand Down
30 changes: 30 additions & 0 deletions silent/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[package]
name = "silent"
edition = "2021"
authors = ["Hubert Shelley <[email protected]>"]
categories = ["web-programming::web", "web-programming::web-framework"]
documentation = "https://docs.rs/"
description = """
Silent Web Framework
"""
homepage = "https://github.com/hubertshelley/silent"
keywords = ["web", "web-framework"]
license = "Apache-2.0"
readme = "./readme.md"
repository = "https://github.com/hubertshelley/silent"
version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
thiserror = "1"
hyper = { version = "1.0.0-rc.3", features = ["full"] }
tokio = { version = "1", features = ["full"] }
bytes = "1"
http-body-util = "0.1.0-rc.2"
#salvo_core = { git = "https://github.com/hubertshelley/salvo.git" }
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
async-trait = "0.1.68"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
uuid = "1.3.2"
18 changes: 18 additions & 0 deletions silent/src/conn/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use crate::rt::RtExecutor;
use hyper::server::conn::{http1, http2};

#[doc(hidden)]
#[allow(dead_code)]
pub struct SilentConnection {
pub(crate) http1: http1::Builder,
pub(crate) http2: http2::Builder<RtExecutor>,
}

impl Default for SilentConnection {
fn default() -> Self {
Self {
http1: http1::Builder::new(),
http2: http2::Builder::new(RtExecutor),
}
}
}
5 changes: 5 additions & 0 deletions silent/src/core/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub(crate) mod path_param;
pub(crate) mod req_body;
pub(crate) mod request;
pub(crate) mod res_body;
pub(crate) mod response;
27 changes: 27 additions & 0 deletions silent/src/core/path_param.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use uuid::Uuid;

#[derive(Debug, PartialEq)]
pub enum PathParam {
String(String),
Int(i32),
UUid(Uuid),
Path(String),
}

impl From<String> for PathParam {
fn from(s: String) -> Self {
PathParam::String(s)
}
}

impl From<i32> for PathParam {
fn from(i: i32) -> Self {
PathParam::Int(i)
}
}

impl From<Uuid> for PathParam {
fn from(u: Uuid) -> Self {
PathParam::UUid(u)
}
}
19 changes: 19 additions & 0 deletions silent/src/core/req_body.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use hyper::body::Incoming;

#[derive(Debug)]
pub enum ReqBody {
Empty(()),
Incoming(Incoming),
}

impl From<Incoming> for ReqBody {
fn from(incoming: Incoming) -> Self {
Self::Incoming(incoming)
}
}

impl From<()> for ReqBody {
fn from(_: ()) -> Self {
Self::Empty(())
}
}
69 changes: 69 additions & 0 deletions silent/src/core/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use crate::core::path_param::PathParam;
use crate::core::req_body::ReqBody;
use hyper::Request as HyperRequest;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};

#[derive(Debug)]
pub struct Request {
req: HyperRequest<ReqBody>,
pub path_params: HashMap<String, PathParam>,
}

impl Default for Request {
fn default() -> Self {
Self::empty()
}
}

impl Request {
pub fn empty() -> Self {
Self {
req: HyperRequest::builder()
.method("GET")
.body(().into())
.unwrap(),
path_params: HashMap::new(),
}
}

pub(crate) fn set_path_params(&mut self, key: String, value: PathParam) {
self.path_params.insert(key, value);
}

pub fn path_params(&self) -> &HashMap<String, PathParam> {
&self.path_params
}

pub fn get_path_params(&self, key: &str) -> Option<&PathParam> {
self.path_params.get(key)
}

pub(crate) fn split_url(self) -> (Self, String) {
let url = self.uri().to_string();
(self, url)
}
}

impl From<HyperRequest<ReqBody>> for Request {
fn from(req: HyperRequest<ReqBody>) -> Self {
Self {
req,
..Self::default()
}
}
}

impl Deref for Request {
type Target = HyperRequest<ReqBody>;

fn deref(&self) -> &Self::Target {
&self.req
}
}

impl DerefMut for Request {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.req
}
}
10 changes: 10 additions & 0 deletions silent/src/core/res_body.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use bytes::Bytes;
use http_body_util::{BodyExt, Full};

pub type ResBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;

pub fn full<T: Into<Bytes>>(chunk: T) -> ResBody {
Full::new(chunk.into())
.map_err(|never| match never {})
.boxed()
}
55 changes: 55 additions & 0 deletions silent/src/core/response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use crate::core::res_body::{full, ResBody};
use bytes::Bytes;
use hyper::Response as HyperResponse;
use std::ops::{Deref, DerefMut};

#[derive(Debug)]
pub struct Response {
pub res: HyperResponse<ResBody>,
}

impl Response {
pub fn empty() -> Self {
Response::from(Bytes::new())
}
#[allow(dead_code)]
pub fn set_status(&mut self, status: hyper::StatusCode) {
*self.res.status_mut() = status;
}
#[allow(dead_code)]
pub fn set_body(mut self, body: ResBody) -> Self {
*self.res.body_mut() = body;
self
}
#[allow(dead_code)]
pub fn set_header(
&mut self,
key: hyper::header::HeaderName,
value: hyper::header::HeaderValue,
) -> &mut Self {
self.headers_mut().insert(key, value);
self
}
}

impl<T: Into<Bytes>> From<T> for Response {
fn from(chunk: T) -> Self {
Self {
res: HyperResponse::new(full(chunk)),
}
}
}

impl Deref for Response {
type Target = HyperResponse<ResBody>;

fn deref(&self) -> &Self::Target {
&self.res
}
}

impl DerefMut for Response {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.res
}
}
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 20a5d4f

Please sign in to comment.