Skip to content

Commit

Permalink
Merge pull request #3 from hubertshelley/develop
Browse files Browse the repository at this point in the history
v0.2.1 publish
  • Loading branch information
hubertshelley authored May 5, 2023
2 parents 20a5d4f + 9c9ad60 commit b15c3b1
Show file tree
Hide file tree
Showing 22 changed files with 1,173 additions and 61 deletions.
2 changes: 1 addition & 1 deletion deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ allow = [
# "Apache-2.0 WITH LLVM-exception",
# "ISC",
"Unicode-DFS-2016",
# "BSD-3-Clause",
"BSD-3-Clause",
# "BSD-2-Clause",
]
# List of explicitly disallowed licenses
Expand Down
10 changes: 10 additions & 0 deletions examples/form/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "example-form"
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" }
serde = { version = "1.0.160", features = ["derive"] }
43 changes: 43 additions & 0 deletions examples/form/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use serde::{Deserialize, Serialize};
use silent::prelude::*;

fn main() {
logger::fmt().init();
let route = Route::new("").get_html(show_form).post(accept_form);
Server::new().bind_route(route).run();
}

#[derive(Deserialize, Serialize, Debug)]
#[allow(dead_code)]
struct Input {
name: String,
email: String,
}

async fn accept_form(mut req: Request) -> Result<Option<Input>, SilentError> {
req.json_parse().await
}

async fn show_form(_req: Request) -> Result<&'static str, SilentError> {
Ok(r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post">
<label for="name">
Enter your name:
<input type="text" name="name">
</label>
<label>
Enter your email:
<input type="text" name="email">
</label>
<input type="submit" value="Subscribe!">
</form>
</body>
</html>
"#)
}
2 changes: 1 addition & 1 deletion examples/hello-world/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ 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" }
silent = { path = "../../silent" }
10 changes: 10 additions & 0 deletions examples/multipart-form/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "example-multipart-form"
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" }
serde = { version = "1.0.160", features = ["derive"] }
46 changes: 46 additions & 0 deletions examples/multipart-form/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use serde::{Deserialize, Serialize};
use silent::prelude::*;

fn main() {
logger::fmt().init();
let route = Route::new("").get_html(show_form).post(accept_form);
Server::new().bind_route(route).run();
}

async fn show_form(_req: Request) -> Result<&'static str, SilentError> {
Ok(r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label>
Upload file:
<input type="file" name="files" multiple>
</label>
<input type="submit" value="Upload files">
</form>
</body>
</html>
"#)
}

#[derive(Debug, Deserialize, Serialize, Default)]
struct File {
name: String,
file_name: String,
}

async fn accept_form(mut req: Request) -> Result<Vec<File>, SilentError> {
let mut result_files = vec![];
if let Some(files) = req.files("files").await {
for file in files {
result_files.push(File {
name: file.name().unwrap_or("file").to_string(),
file_name: file.path().to_string_lossy().to_string(),
});
}
}
Ok(result_files)
}
4 changes: 2 additions & 2 deletions examples/path_params/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[package]
name = "path_params"
name = "example-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" }
silent = { path = "../../silent" }
12 changes: 12 additions & 0 deletions examples/todo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "example-todo"
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" }
serde = { version = "1.0.160", features = ["derive"] }
uuid = { version = "1.3.2", features = ["serde", "v4"] }
async-trait = "0.1.68"
150 changes: 150 additions & 0 deletions examples/todo/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use silent::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use uuid::Uuid;

fn main() {
logger::fmt().init();
let db = Db::default();
let middle_ware = MiddleWare { db };
let route = Route::new("todos")
.hook(middle_ware)
.get(todos_index)
.post(todos_create)
.append(
Route::new("<id:uuid>")
.patch(todos_update)
.delete(todos_delete),
);
Server::new().bind_route(route).run();
}

struct MiddleWare {
db: Db,
}

#[async_trait]
impl Handler for MiddleWare {
async fn middleware_call(
&self,
req: &mut Request,
_res: &mut Response,
) -> Result<(), SilentError> {
req.extensions_mut().insert(self.db.clone());
Ok(())
}
}

#[derive(Debug, Deserialize, Default)]
pub struct Pagination {
pub offset: Option<usize>,
pub limit: Option<usize>,
}

async fn todos_index(mut req: Request) -> Result<Vec<Todo>, SilentError> {
let pagination = req.params_parse::<Pagination>()?;

let db = req.extensions().get::<Db>().unwrap();
let todos = db.read().unwrap();

let todos = todos
.values()
.skip(pagination.offset.unwrap_or(0))
.take(pagination.limit.unwrap_or(usize::MAX))
.cloned()
.collect::<Vec<_>>();

Ok(todos)
}

#[derive(Debug, Deserialize)]
struct CreateTodo {
text: String,
}

async fn todos_create(mut req: Request) -> Result<Todo, SilentError> {
let create_todo = req.json_parse::<CreateTodo>().await?;
let db = req.extensions().get::<Db>().unwrap();

let todo = Todo {
id: Uuid::new_v4(),
text: create_todo.text,
completed: false,
};

db.write().unwrap().insert(todo.id, todo.clone());

Ok(todo)
}

#[derive(Debug, Deserialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
}

async fn todos_update(mut req: Request) -> Result<Todo, SilentError> {
let input = req.json_parse::<UpdateTodo>().await?;
let db = req.extensions().get::<Db>().unwrap();
let id = req.get_path_params("id").unwrap();
if let PathParam::UUid(id) = id {
let todo = db.read().unwrap().get(id).cloned();

if todo.is_none() {
return Err(SilentError::BusinessError {
code: StatusCode::NOT_FOUND,
msg: "Not Found".to_string(),
});
}

let mut todo = todo.unwrap();

if let Some(text) = input.text {
todo.text = text;
}

if let Some(completed) = input.completed {
todo.completed = completed;
}

db.write().unwrap().insert(todo.id, todo.clone());

Ok(todo)
} else {
Err(SilentError::BusinessError {
code: StatusCode::NOT_FOUND,
msg: "Not Found".to_string(),
})
}
}

async fn todos_delete(req: Request) -> Result<(), SilentError> {
let db = req.extensions().get::<Db>().unwrap();
let id = req.get_path_params("id").unwrap();
if let PathParam::UUid(id) = id {
if db.write().unwrap().remove(id).is_some() {
Ok(())
} else {
Err(SilentError::BusinessError {
code: StatusCode::NOT_FOUND,
msg: "Not Found".to_string(),
})
}
} else {
Err(SilentError::BusinessError {
code: StatusCode::NOT_FOUND,
msg: "Not Found".to_string(),
})
}
}

type Db = Arc<RwLock<HashMap<Uuid, Todo>>>;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct Todo {
id: Uuid,
text: String,
completed: bool,
}
23 changes: 15 additions & 8 deletions silent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ Silent Web Framework
homepage = "https://github.com/hubertshelley/silent"
keywords = ["web", "web-framework"]
license = "Apache-2.0"
readme = "./readme.md"
readme = "../readme.md"
repository = "https://github.com/hubertshelley/silent"
version = "0.1.0"
version = "0.2.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
Expand All @@ -21,10 +21,17 @@ 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"
tracing = "0.1"
tracing-subscriber = "0.3"
async-trait = "0.1"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
uuid = "1.3.2"
serde_json = "1"
uuid = "1"
url = "2"
serde_urlencoded = "0.7"
multimap = { version = "0.9", features = ["serde"] }
mime = "0.3"
tempfile = "3"
textnonce = "1"
multer = "2"
futures-util = { version = "0.3", features = ["io"] }
Loading

0 comments on commit b15c3b1

Please sign in to comment.