Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions examples/form/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ struct Input {
email: String,
}

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

async fn show_form(_req: Request) -> Result<&'static str> {
Ok(r#"
async fn show_form(_req: Request) -> Result<Response> {
Ok(Response::html(
r#"
<!doctype html>
<html>
<head></head>
Expand All @@ -39,5 +40,6 @@ async fn show_form(_req: Request) -> Result<&'static str> {
</form>
</body>
</html>
"#)
"#,
))
}
4 changes: 1 addition & 3 deletions examples/get_real_ip/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ use silent::prelude::*;
fn main() {
logger::fmt().with_max_level(Level::INFO).init();
let route = Route::new("").get(|req| async move { Ok(req.remote().to_string()) });
Server::new()
.bind("0.0.0.0:8000".parse().unwrap())
.run(route);
Server::new().run(route);
}
4 changes: 2 additions & 2 deletions examples/sse-chat/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use futures_util::StreamExt;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;

Expand Down Expand Up @@ -40,7 +40,7 @@ enum Message {
Reply(String),
}

#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Clone, Deserialize, Serialize)]
struct Msg {
msg: String,
}
Expand Down
4 changes: 2 additions & 2 deletions examples/todo/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async fn todos_index(mut req: Request) -> Result<Vec<Todo>> {
Ok(todos)
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
struct CreateTodo {
text: String,
}
Expand All @@ -76,7 +76,7 @@ async fn todos_create(mut req: Request) -> Result<Todo> {
Ok(todo)
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
struct UpdateTodo {
text: Option<String>,
completed: Option<bool>,
Expand Down
61 changes: 38 additions & 23 deletions silent/src/core/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use http::{Extensions, HeaderMap, HeaderValue, Method, Uri, Version};
use http::{Request as BaseRequest, StatusCode};
use http_body_util::BodyExt;
use mime::Mime;
use serde::Deserialize;
use serde::de::StdError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use tokio::sync::OnceCell;
Expand Down Expand Up @@ -293,7 +293,9 @@ impl Request {
#[cfg(feature = "multipart")]
#[inline]
pub async fn form_data(&mut self) -> Result<&FormData> {
let content_type = self.content_type().ok_or(SilentError::ContentTypeError)?;
let content_type = self
.content_type()
.ok_or(SilentError::ContentTypeMissingError)?;
if content_type.subtype() != mime::FORM_DATA {
return Err(SilentError::ContentTypeError);
}
Expand Down Expand Up @@ -343,17 +345,22 @@ impl Request {
pub async fn json_parse<T>(&mut self) -> Result<T>
where
for<'de> T: Deserialize<'de>,
T: Serialize,
{
let body = self.take_body();
let content_type = self.content_type().ok_or(SilentError::ContentTypeError)?;
if content_type.subtype() != mime::JSON {
let content_type = self
.content_type()
.ok_or(SilentError::ContentTypeMissingError)?;
if content_type.subtype() != mime::JSON
&& content_type.subtype() != mime::WWW_FORM_URLENCODED
{
return Err(SilentError::ContentTypeError);
}
match body {
ReqBody::Incoming(body) => {
let value = self
.json_data
.get_or_try_init(|| async {
let value = self
.json_data
.get_or_try_init(|| async {
let value = match body {
ReqBody::Incoming(body) => {
let bytes = body
.collect()
.await
Expand All @@ -362,20 +369,28 @@ impl Request {
if bytes.is_empty() {
return Err(SilentError::JsonEmpty);
}
serde_json::from_slice(&bytes).map_err(|e| e.into())
})
.await?;
Ok(serde_json::from_value(value.to_owned())?)
}
ReqBody::Once(bytes) => match content_type.subtype() {
mime::WWW_FORM_URLENCODED => {
serde_html_form::from_bytes(&bytes).map_err(SilentError::from)
}
mime::JSON => serde_json::from_slice(&bytes).map_err(|e| e.into()),
_ => Err(SilentError::JsonEmpty),
},
ReqBody::Empty => Err(SilentError::BodyEmpty),
}
match content_type.subtype() {
mime::WWW_FORM_URLENCODED => {
serde_html_form::from_bytes::<T>(&bytes).map_err(SilentError::from)
}
mime::JSON => serde_json::from_slice::<T>(&bytes).map_err(|e| e.into()),
_ => Err(SilentError::JsonEmpty),
}
}
ReqBody::Once(bytes) => match content_type.subtype() {
mime::WWW_FORM_URLENCODED => {
serde_html_form::from_bytes(&bytes).map_err(SilentError::from)
}
mime::JSON => serde_json::from_slice(&bytes).map_err(|e| e.into()),
_ => Err(SilentError::JsonEmpty),
},
ReqBody::Empty => Err(SilentError::BodyEmpty),
}?;
serde_json::to_value(&value).map_err(|e| e.into())
})
.await?
.clone();
serde_json::from_value(value).map_err(Into::into)
}

/// 转换body参数按Json匹配
Expand Down
5 changes: 4 additions & 1 deletion silent/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ pub enum SilentError {
/// Json为空 错误
#[error("json is empty")]
JsonEmpty,
/// Json为空 错误
/// Content-Type 错误
#[error("content-type is error")]
ContentTypeError,
/// Content-Type 缺失错误
#[error("content-type is missing")]
ContentTypeMissingError,
/// Params为空 错误
#[error("params is empty")]
ParamsEmpty,
Expand Down
Loading