Skip to content

Commit

Permalink
[ISSUES#83] extra body param part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
847850277 committed Dec 1, 2024
1 parent e3bf9da commit c8043a2
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 132 deletions.
1 change: 1 addition & 0 deletions hyper-examples-1/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use hyper::{Body, Request, Response, Server};
use tokio::runtime::Runtime;

async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
//req.into_parts();
let mut body = req.into_body();
let mut data = Vec::new();

Expand Down
5 changes: 5 additions & 0 deletions mario-core/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# 获取body 参数

- 参考hyper-examples-1,能够进行参数的提取,
- 只需要怎么把body转换一下就行了
- debug into_body干了啥
12 changes: 10 additions & 2 deletions mario-core/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
use crate::error::Error;
use crate::request::Request;
use crate::response::Response;
use http::Request;
use hyper::body::Incoming;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;

pub trait Endpoint: Debug + Sync + Send {
fn call(&self, req: &Request) -> Result<Response<String>, Error>;
//fn call(&self, req: Request<Incoming>) -> Result<Response<String>, Error>;

fn call(
&self,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>>;
}
1 change: 0 additions & 1 deletion mario-core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
pub mod error;
pub mod extra;
pub mod handler;
pub mod request;
pub mod response;
pub mod route;
pub mod server;
Expand Down
57 changes: 0 additions & 57 deletions mario-core/src/request.rs

This file was deleted.

14 changes: 9 additions & 5 deletions mario-core/src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use http::Method;
use http::{Method, Request};
use hyper::body::Incoming;
use route_recognizer::{Match, Params, Router as InternalRouter};

use crate::error::Error;
use crate::handler::Endpoint;
use crate::response::Response;

pub struct RouterMatch<'a> {
pub handler: &'a dyn Endpoint,
Expand All @@ -21,10 +23,12 @@ struct NotFound;
impl Endpoint for NotFound {
fn call(
&self,
_req: &crate::request::Request,
) -> Result<crate::response::Response<String>, Error> {
let response = "Not Found";
Ok(crate::response::Response::new(response.to_string()))
_req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
let response = "Not Found";
Ok(crate::response::Response::new(response.to_string()))
})
}
}

Expand Down
6 changes: 2 additions & 4 deletions mario-core/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use hyper_util::server::conn::auto::Builder;
use tokio::net::{TcpListener, TcpStream};
use tracing::info;

use crate::request::Request as MarioRequest;
use crate::route::Router;
use crate::service::Service;

Expand Down Expand Up @@ -50,10 +49,9 @@ async fn dispatch(
request: Request<hyper::body::Incoming>,
service: Arc<Service>,
) -> Result<Response<Full<Bytes>>, Infallible> {
let request = MarioRequest::new(request);
let router = service.get_routes();
let router_match = router.route(request.head.uri.path(), &request.method());
let response = router_match.handler.call(&request);
let router_match = router.route(request.uri().path(), request.method());
let response = router_match.handler.call(request).await;
match response {
Ok(response) => {
let body = response.get_body().to_string();
Expand Down
10 changes: 7 additions & 3 deletions mario-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,16 @@ fn generate_handler(_args: TokenStream, input: TokenStream) -> syn::Result<Token
}

impl Endpoint for #ident {
fn call(&self, req: &mario_core::request::Request) -> Result<Response<String>, Error>{
fn call(&self, req: Request<Incoming>) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>>{
#item_fn
let fut = #ident();
let response = fut;
Ok(Response::new(response.to_string()))
// let response = fut;
// Ok(Response::new(response.to_string()))

Box::pin(async move {
let response = fut.await;
Ok(Response::new(response.to_string()))
})

}
}
Expand Down
5 changes: 3 additions & 2 deletions mario-rs-examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ edition.workspace = true
tokio.workspace = true
mario-core = { workspace = true }
mario-macro = { workspace = true }
hyper.workspace = true
http-body.workspace = true
http-body-util.workspace = true
tracing-subscriber.workspace = true
http.workspace = true
log.workspace = true
futures.workspace = true
warp.workspace = true
serde_urlencoded = "0.7.1"
serde_urlencoded = "0.7.1"
151 changes: 93 additions & 58 deletions mario-rs-examples/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use ::hyper::body::Incoming;
use http::Request;
use http_body_util::{BodyExt, Full};
use log::info;
use mario_core::error::Error;
Expand All @@ -12,9 +14,12 @@ use std::future::Future;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::Arc;
use tokio::runtime::Runtime;
use warp::body::bytes;
use warp::hyper;
use warp::hyper::body;
use warp::hyper::body::Bytes;
use warp::hyper::body::HttpBody;
use warp::hyper::body::{to_bytes, Bytes};
use warp::hyper::{body, Body};

async fn example() -> Response<String> {
Response::new("run example".to_string())
Expand Down Expand Up @@ -49,98 +54,128 @@ fn example_4<T: std::fmt::Display>(
pub struct ExampleHandler;

impl Endpoint for ExampleHandler {
fn call(&self, _req: &mario_core::request::Request) -> Result<Response<String>, Error> {
let response = example_1();
Ok(Response::new(response.to_string()))
fn call(
&self,
_req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
let response = example_1();
Ok(Response::new(response.to_string()))
})
}
}

#[handler]
fn hello() -> i32 {
async fn hello() -> i32 {
2
}

#[handler]
fn world() -> String {
async fn world() -> String {
"example_3".to_string()
}

#[derive(Debug, Default)]
pub struct ExtraExample;

impl Endpoint for ExtraExample {
fn call(&self, req: &mario_core::request::Request) -> Result<Response<String>, Error> {
let copy_req = Arc::new(req);
let query = copy_req.head.uri.query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() > 0 {
let response = example_2(Query(result[0].1.clone()));
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
fn call(
&self,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
let query = req.uri().query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() > 0 {
let response = example_2(Query(result[0].1.clone()));
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
})
}
}

#[derive(Debug, Default)]
pub struct ExtraMultiExample;

impl Endpoint for ExtraMultiExample {
fn call(&self, req: &mario_core::request::Request) -> Result<Response<String>, Error> {
let copy_req = Arc::new(req);
let query = copy_req.head.uri.query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() >= 2 {
let response = example_3(Query(result[0].1.clone()), Query(result[1].1.clone()));
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
fn call(
&self,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
let query = req.uri().query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() >= 2 {
let response = example_3(Query(result[0].1.clone()), Query(result[1].1.clone()));
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
})
}
}

#[derive(Debug, Default)]
pub struct ExtraMulti_2Example;

impl Endpoint for ExtraMulti_2Example {
fn call(&self, req: &mario_core::request::Request) -> Result<Response<String>, Error> {
let copy_req = Arc::new(req);
let query = copy_req.head.uri.query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() >= 3 {
let response = example_4(
Query(result[0].1.clone()),
Query(result[1].1.clone()),
Query(result[2].1.clone()),
);
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
fn call(
&self,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
let query = req.uri().query().unwrap_or_default();
info!("query: {:?}", query);
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(query);
let result = match result {
Ok(result) => result,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
if result.len() >= 3 {
let response = example_4(
Query(result[0].1.clone()),
Query(result[1].1.clone()),
Query(result[2].1.clone()),
);
return Ok(Response::new(response.to_string()));
}
Ok(Response::new("not param".to_string()))
})
}
}

#[derive(Debug, Default)]
pub struct ExtraPostExample;

impl Endpoint for ExtraPostExample {
fn call(&self, req: &mario_core::request::Request) -> Result<Response<String>, Error> {
dbg!(req);
let body = &req.body;
dbg!(body);
Ok(Response::new("not param".to_string()))
fn call(
&self,
req: Request<Incoming>,
) -> Pin<Box<dyn Future<Output = Result<Response<String>, Error>> + Send>> {
Box::pin(async move {
// Incoming to Body
//let req = convert_request(req);
let body = req.into_body();
let collect = body.collect();
let body = collect.await;
let body = match body {
Ok(body) => body,
Err(_) => return Ok(Response::new("500 Internal Server Error".to_string())),
};
//println!("body: {:?}", body);
let response = format!("body: {:?}", body);
Ok(Response::new(response))
})
}
}

Expand Down

0 comments on commit c8043a2

Please sign in to comment.