Skip to content

Commit

Permalink
Merge pull request #81 from kana-rus/fix_around_request_handling
Browse files Browse the repository at this point in the history
Fix around request handling
  • Loading branch information
kanarus authored Feb 8, 2024
2 parents 78d810b + 6fb1a93 commit 8f3cbc5
Show file tree
Hide file tree
Showing 25 changed files with 267 additions and 214 deletions.
21 changes: 16 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
- *multi runtime* support:`tokio`, `async-std`

<div align="right">
<img alt="build check status of ohkami" src="https://github.com/kana-rus/ohkami/actions/workflows/CI.yml/badge.svg"/>
<a href="https://github.com/kana-rus/ohkami/actions"><img alt="build check status of ohkami" src="https://github.com/kana-rus/ohkami/actions/workflows/CI.yml/badge.svg"/></a>
<a href="https://crates.io/crates/ohkami"><img alt="crates.io" src="https://img.shields.io/crates/v/ohkami" /></a>
<a href="https://github.com/kana-rus/ohkami/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/crates/l/ohkami.svg" /></a>
</div>

<br>
Expand Down Expand Up @@ -47,7 +49,7 @@ async fn main() {
.GET(health_check),
"/hello/:name"
.GET(hello),
)).howl(3000).await
)).howl("localhost:3000").await
}
```

Expand Down Expand Up @@ -152,7 +154,7 @@ impl IntoFang for LogRequest {
async fn main() {
Ohkami::with((AppendHeaders, LogRequest), (
"/".GET(|| async {"Hello!"})
)).howl(":8080").await
)).howl("localhost:8080").await
}
```
Expand Down Expand Up @@ -202,7 +204,7 @@ async fn main() {
Ohkami::new((
"/healthz" .GET(health_check),
"/api/users".By(users_ohkami), // <-- nest by `By`
)).howl(5000).await
)).howl("localhost:5000").await
}
```

Expand Down Expand Up @@ -239,8 +241,17 @@ async fn test_my_ohkami() {

<br>

## Supporting protocol
- [x] HTTP/1.1
- [ ] HTTPS
- [ ] HTTP/2
- [ ] HTTP/3
- [ ] WebSocket

<br>

## MSRV (Minimum Supported Rust Version)
Latest stable.

## License
`ohkami` is licensed under MIT LICENSE ([LICENSE-MIT](https://github.com/kana-rus/ohkami/blob/main/LICENSE-MIT) or [https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT)).
`ohkami` is licensed under MIT LICENSE ([LICENSE](https://github.com/kana-rus/ohkami/blob/main/LICENSE) or [https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT)).
5 changes: 3 additions & 2 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ members = [
]

[workspace.dependencies]
ohkami = { version = "0.13.0", path = "../ohkami", features = ["rt_tokio"] }
# To assure "DEBUG" feature be off even if DEBUGing `../ohkami`,
# explicitly set `default-features = false`
ohkami = { version = "0.13.0", path = "../ohkami", default-features = false, features = ["rt_tokio", "utils", "testing"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
sqlx = { version = "0.7.3", features = ["runtime-tokio-native-tls", "postgres", "macros", "chrono", "uuid"] }
tracing = "0.1"
tracing-subscriber = "0.3"
Expand Down
1 change: 0 additions & 1 deletion examples/form/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,5 @@ edition = "2021"
[dependencies]
ohkami = { workspace = true }
tokio = { workspace = true }
serde = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
2 changes: 1 addition & 1 deletion examples/form/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ async fn main() {
Ohkami::with(Logger, (
"/form" .GET(get_form),
"/submit".POST(post_submit),
)).howl(5000).await
)).howl("localhost:5000").await
}
1 change: 0 additions & 1 deletion examples/hello/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,5 @@ edition = "2021"
[dependencies]
ohkami = { workspace = true }
tokio = { workspace = true }
serde = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
13 changes: 6 additions & 7 deletions examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ mod hello_handler {
}


#[Payload(JSON)]
#[derive(serde::Deserialize)]
#[Payload(JSOND)]
pub struct HelloRequest<'n> {
name: &'n str,
repeat: Option<usize>,
Expand Down Expand Up @@ -73,9 +72,9 @@ mod fangs {
.Server("ohkami");

tracing::info!("\
Called `append_server`\n\
Called `SetServer`\n\
[current headers]\n\
{:?}\
{:?}\n\
", res.headers);
})
}
Expand All @@ -88,7 +87,7 @@ mod fangs {
let __method__ = req.method();
let __path__ = req.path();

tracing::info!("\
tracing::info!("\n\
Got request:\n\
[ method ] {__method__}\n\
[ path ] {__path__}\n\
Expand Down Expand Up @@ -117,8 +116,8 @@ async fn main() {

tracing::info!("Started listening on http://localhost:3000");

Ohkami::with(LogRequest, (
Ohkami::with((LogRequest,), (
"/hc" .GET(health_handler::health_check),
"/api".By(hello_ohkami),
)).howl(3000).await
)).howl("localhost:3000").await
}
2 changes: 1 addition & 1 deletion examples/quick_start/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ async fn main() {
GET(health_check),
"/hello/:name".
GET(hello),
)).howl(3000).await
)).howl("localhost:3000").await
}
2 changes: 1 addition & 1 deletion ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ tokio = { version = "1", optional = true, features = ["net", "rt", "io-u
async-std = { version = "1", optional = true }
byte_reader = { version = "2.0.0", features = ["text"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json = { version = "1.0" }
sha1 = { version = "=0.11.0-pre.0", optional = true, default-features = false }
sha2 = { version = "=0.11.0-pre.0", default-features = false }
hmac = { version = "=0.13.0-pre.0", default-features = false }
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/fang/builtin/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::{IntoFang, Fang, Response, Request, append, Status, Method};
/// "/api".GET(|| async {
/// "Hello, CORS!"
/// }),
/// )).howl(8080).await
/// )).howl("localhost:8080").await
/// }
/// ```
pub struct CORS {
Expand Down
15 changes: 7 additions & 8 deletions ohkami/src/fang/builtin/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ use crate::{Request, Response, Status};
/// Ohkami::with(MyAuthFang, (
/// "/signin".POST(signin),
/// "/api/profile".GET(get_profile),
/// )).howl(3000).await
/// )).howl("localhost:3000").await
/// }
/// ```
#[derive(Clone)]
Expand Down Expand Up @@ -327,8 +327,7 @@ impl JWT {
use crate::{testing::*, Memory};
use crate::typed::{ResponseBody, status::OK};

use std::{sync::OnceLock, collections::HashMap, borrow::Cow};
use crate::__rt__::Mutex;
use std::{sync::OnceLock, sync::Mutex, collections::HashMap, borrow::Cow};


fn my_jwt() -> JWT {
Expand Down Expand Up @@ -399,7 +398,7 @@ impl JWT {
}

async fn get_profile(jwt_payload: Memory<'_, MyJWTPayload>) -> Result<OK<Profile>, APIError> {
let r = &mut *repository().await.lock().await;
let r = &mut *repository().await.lock().unwrap();

let user = r.get(&jwt_payload.user_id)
.ok_or_else(|| APIError::UserNotFound)?;
Expand All @@ -421,7 +420,7 @@ impl JWT {
}

async fn signin(body: SigninRequest<'_>) -> utils::Text {
let r = &mut *repository().await.lock().await;
let r = &mut *repository().await.lock().unwrap();

let user: Cow<'_, User> = match r.iter().find(|(_, u)|
u.first_name == body.first_name &&
Expand Down Expand Up @@ -510,7 +509,7 @@ impl JWT {


assert_eq! {
&*repository().await.lock().await,
&*repository().await.lock().unwrap(),
&HashMap::from([
(1, User {
id: 1,
Expand Down Expand Up @@ -542,7 +541,7 @@ impl JWT {


assert_eq! {
&*repository().await.lock().await,
&*repository().await.lock().unwrap(),
&HashMap::from([
(1, User {
id: 1,
Expand Down Expand Up @@ -576,7 +575,7 @@ impl JWT {


assert_eq! {
&*repository().await.lock().await,
&*repository().await.lock().unwrap(),
&HashMap::from([
(1, User {
id: 1,
Expand Down
18 changes: 14 additions & 4 deletions ohkami/src/fang/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod builtin;

use std::sync::Arc;
use std::{any::{Any, TypeId}, sync::Arc};
use crate::{Request, Response};


Expand Down Expand Up @@ -31,7 +31,7 @@ use crate::{Request, Response};
/// "/".GET(|| async {
/// "Hello!"
/// })
/// ).howl(5000).await
/// ).howl("localhost:5000").await
/// }
/// ```
///
Expand All @@ -52,13 +52,21 @@ use crate::{Request, Response};
/// Hello!
#[derive(Clone)]
pub struct Fang {
id: TypeId,
pub(crate) proc: proc::FangProc,
}
impl Fang {
pub(crate) fn is_front(&self) -> bool {
matches!(self.proc, proc::FangProc::Front(_))
}
}
const _: () = {
impl<'f> PartialEq for &'f Fang {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
};

pub(crate) mod proc {
use std::sync::Arc;
Expand Down Expand Up @@ -94,8 +102,9 @@ const _: () = {
///
/// - `Fn(&/&mut Request)`
/// - `Fn(&/&mut Request) -> Result<(), Response>`
pub fn front<M>(material: impl IntoFrontFang<M>) -> Self {
pub fn front<M>(material: impl IntoFrontFang<M> + 'static) -> Self {
Self {
id: material.type_id(),
proc: proc::FangProc::Front(material.into_front()),
}
}
Expand All @@ -106,8 +115,9 @@ const _: () = {
/// - `Fn(&/&mut Response) -> Result<(), Response>`
/// - `Fn(&/&mut Response, &Request)`
/// - `Fn(&/&mut Response, &Request) -> Result<(), Response>`
pub fn back<M>(material: impl IntoBackFang<M>) -> Self {
pub fn back<M>(material: impl IntoBackFang<M> + 'static) -> Self {
Self {
id: material.type_id(),
proc: proc::FangProc::Back(material.into_back()),
}
}
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/handler/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ macro_rules! Route {
/// "/hello" // <-- `Route` works here...
/// .GET(greet)
/// .PUT(hello),
/// )).howl(3000).await
/// )).howl("localhost:3000").await
/// }
/// ```
pub trait Route {
Expand Down
18 changes: 5 additions & 13 deletions ohkami/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,10 @@ mod __rt__ {
#[cfg(all(feature="rt_async-std", feature="DEBUG"))]
pub(crate) use async_std::test;

#[cfg(all(feature="websocket", feature="rt_tokio"))]
pub(crate) use tokio::net::TcpStream;
#[cfg(all(feature="websocket", feature="rt_async-std"))]
pub(crate) use async_std::net::TcpStream;

#[cfg(feature="rt_tokio")]
pub(crate) use tokio::net::TcpListener;
#[cfg(feature="rt_async-std")]
pub(crate) use async_std::net::TcpListener;

#[cfg(feature="rt_tokio")]
pub(crate) use tokio::sync::Mutex;
#[allow(unused)]
pub(crate) use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
#[cfg(feature="rt_async-std")]
pub(crate) use async_std::sync::Mutex;
pub(crate) use async_std::net::{TcpListener, TcpStream, ToSocketAddrs};

#[cfg(feature="rt_tokio")]
pub(crate) use tokio::task;
Expand Down Expand Up @@ -88,6 +77,9 @@ pub use handler::Route;
mod fang;
pub use fang::{Fang, builtin};

mod session;
use session::Session;

mod ohkami;
pub use ohkami::{Ohkami, IntoFang};

Expand Down
Loading

0 comments on commit 8f3cbc5

Please sign in to comment.