Skip to content

Commit

Permalink
refactor: rename Chain struct to Middlewares
Browse files Browse the repository at this point in the history
- Improve documentation and fix all doc examples
- MSRV 1.56.0
- Update dependencies
- Addci pipelines
  • Loading branch information
joseluisq committed Feb 5, 2024
1 parent c0b80a2 commit c0aa9cf
Show file tree
Hide file tree
Showing 11 changed files with 334 additions and 111 deletions.
2 changes: 2 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github: joseluisq
custom: paypal.me/joseluisqs
28 changes: 28 additions & 0 deletions .github/workflows/audit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: audit
on:
schedule:
- cron: '20 01 * * *' # Every day at 01:20 UTC
push:
branches:
- master
paths:
- "**/Cargo.lock"
- "**/Cargo.toml"
pull_request:
branches:
- master
paths:
- "**/Cargo.lock"
- "**/Cargo.toml"

jobs:
audit:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1

- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
151 changes: 151 additions & 0 deletions .github/workflows/devel.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
name: devel
on:
pull_request:
paths:
- .github/workflows/devel.yml
- .cargo/config.toml
- Cargo.lock
- Cargo.toml
- src/**
push:
branches:
- master
- staging
- trying
paths:
- .github/workflows/devel.yml
- Cargo.lock
- Cargo.toml
- src/**
schedule:
- cron: '15 01 * * *' # Every day at 01:15 UTC

jobs:
test:
name: test
runs-on: ${{ matrix.os }}
env:
# Cargo binary
CARGO_BIN: cargo
# When CARGO_BIN is set to CROSS, this is set to `--target matrix.target`
TARGET_FLAGS: ""
# When CARGO_BIN is set to CROSS, TARGET_DIR includes matrix.target
TARGET_DIR: ./target
# Emit backtraces on panics
RUST_BACKTRACE: 1
# Skip tests
SKIP_TESTS: ""
strategy:
matrix:
build:
- pinned
- linux-musl
- linux-gnu
- macos
- windows-msvc
include:
# Specific Rust channels.
# We test against the latest and minimum Rust stable version.
- build: pinned
os: ubuntu-22.04
rust: 1.70.0
# Some of our release builds are generated by a nightly compiler to take
# advantage of the latest optimizations/compile time improvements.
- build: linux-musl
os: ubuntu-22.04
rust: stable
target: x86_64-unknown-linux-musl
- build: linux-gnu
os: ubuntu-22.04
rust: stable
target: x86_64-unknown-linux-gnu
- build: macos
os: macos-12
rust: stable
target: x86_64-apple-darwin
- build: windows-msvc
os: windows-2022
rust: stable
target: x86_64-pc-windows-msvc

steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1

- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}

- name: Set up Cross
if: ${{ !contains(matrix.os, 'windows') && matrix.target != '' }}
shell: bash
run: |
target=''
case "${{ matrix.os }}" in
*macos*)
target=x86_64-apple-darwin
;;
*)
target=x86_64-unknown-linux-musl
;;
esac
echo "Installing cross..."
curl -sSL \
"https://github.com/cross-rs/cross/releases/download/v0.2.5/cross-$target.tar.gz" \
| sudo tar zxf - -C /usr/local/bin/ cross cross-util
cross -V
echo "CARGO_BIN=/usr/local/bin/cross" >> $GITHUB_ENV
- name: Setup Cargo
shell: bash
run: |
if [[ "${{ matrix.target }}" != "" ]]; then
echo "TARGET_FLAGS=--target=${{ matrix.target }}" >> $GITHUB_ENV
echo "TARGET_DIR=./target/${{ matrix.target }}" >> $GITHUB_ENV
fi
echo "cargo command is: ${{ env.CARGO_BIN }}"
echo "target flag is: ${{ env.TARGET_FLAGS }}"
echo "target dir is: ${{ env.TARGET_DIR }}"
- name: Run tests
shell: bash
run: |
${{ env.CARGO_BIN }} test --verbose ${{ env.TARGET_FLAGS }} ${{ env.SKIP_TESTS }}
- name: Run build
shell: bash
run: |
${{ env.CARGO_BIN }} build --example server --verbose ${{ env.TARGET_FLAGS }}
checks:
name: checks
runs-on: ubuntu-22.04

steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1

- name: Install stable toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: rustfmt, clippy

- name: Check formatting
run: |
cargo fmt --all -- --check
- name: Check via Clippy
run: |
cargo clippy --all-features -- -D warnings
- name: Check crate docs
run: |
cargo doc --lib --no-deps
21 changes: 16 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ authors = ["Jose Quintana <https://joseluisq.net>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/static-web-server/hyper-middleware"
documentation = "https://docs.rs/hyper-middleware"
edition = "2018"
edition = "2021"
rust-version = "1.56.0"
categories = ["network-programming", "web-programming::http-server"]
include = [
"src/**/*.rs",
Expand All @@ -25,12 +26,22 @@ keywords = [
]

[dependencies]
hyper = { version = "0.14.27", default-features = false, features = ["server", "tcp"] }
anyhow = "1.0.75"
thiserror = "1.0.50"
async-trait = "0.1.74"
hyper = { version = "0.14.28", default-features = false, features = ["server", "tcp"] }
anyhow = "1.0.79"
thiserror = "1.0.56"
async-trait = "0.1.77"
async-recursion = "1.0.5"

[dev-dependencies]
hyper = { version = "0.14", features = ["tcp", "server", "http1"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"], default-features = false }

[profile.release]
codegen-units = 1
debug = false
debug-assertions = false
lto = "fat"
opt-level = 3
panic = "abort"
rpath = false
strip = true
47 changes: 23 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@
- Compact Middleware and Handler System inspired by [The Iron Framework](https://github.com/iron/iron).
- Simple [Hyper Service](https://docs.rs/hyper/latest/hyper/service/trait.Service.html) with convenient __Remote Address__ access.
- Convenient `Error` and `Result` types powered by [anyhow](https://github.com/dtolnay/anyhow).
- `Async` support via [async-trait](https://github.com/dtolnay/async-trait).
- Macros to facilitate HTTP response errors or error casting.

## Example

[examples/server.rs](examples/server.rs)

```rust
#![deny(warnings)]

use hyper::{header, Server, StatusCode};
use std::{net::SocketAddr, path::PathBuf};
use hyper_middleware::{
async_trait, AfterMiddleware, BeforeMiddleware, Body, Chain, Error, Handler, Request, Response,
Result, Service,
async_trait, AfterMiddleware, BeforeMiddleware, Body, Error, Handler, Middlewares, Request,
Response, Result, Service,
};
use std::{net::SocketAddr, path::PathBuf};

struct Config {
pub root: PathBuf,
Expand All @@ -39,17 +39,18 @@ struct Application {
impl Handler for Application {
async fn handle(&self, req: &mut Request) -> Result<Response> {
// Access the Hyper incoming Request
println!("Handler - URI Path: {}", req.uri().path());
println!("Application::handle() - URI Path: {}", req.uri().path());

// Access the custom app options
println!("Config Root: {}", self.opts.root.display());

// Access the Remote Address
println!(
"Remote Addr: {}",
req.extensions().get::<SocketAddr>().unwrap()
"Application::handle() - Config Root: {}",
self.opts.root.display()
);

// Access the Remote Address
let remote_addr = req.extensions().get::<SocketAddr>().unwrap();
println!("Application::handle() - Remote Addr: {}", remote_addr);

// Create a Hyper Response and send it back to the middlewares chain
Ok(Response::new(Body::from("¡Hola!")))
}
Expand All @@ -60,10 +61,10 @@ struct FirstMiddleware {}
#[async_trait]
impl BeforeMiddleware for FirstMiddleware {
async fn before(&self, req: &mut Request) -> Result {
println!("First Middleware called!");
println!("FirstMiddleware::before()");

// Access the Hyper incoming Request
println!("First - URI Path: {}", req.uri().path());
println!("FirstMiddleware::before() - URI Path: {}", req.uri().path());

Ok(())
}
Expand All @@ -78,7 +79,7 @@ struct SecondMiddleware {}
#[async_trait]
impl AfterMiddleware for SecondMiddleware {
async fn after(&self, _: &mut Request, mut res: Response) -> Result<Response> {
println!("Second Middleware called!");
println!("SecondMiddleware::after()");

// Mutate the Hyper Response at convenience
// and send it back to other middlewares on the chain
Expand All @@ -105,17 +106,15 @@ async fn main() -> Result {
root: std::env::current_dir().unwrap(),
};

// 1. Create a custom middleware chain
let mut handler = Chain::new(Application { opts });
// 1. Create a custom middleware chain and plug in some custom middlewares
let mut middlewares = Middlewares::new(Application { opts });
middlewares.link_before(FirstMiddleware {});
middlewares.link_after(SecondMiddleware {});

// 2. Plug in some custom middlewares
handler.link_before(FirstMiddleware {});
handler.link_after(SecondMiddleware {});
// 2. Create a Hyper service and set the current handler with its middlewares
let service = Service::new(middlewares);

// 3. Create a Hyper service and set the current handler with its middlewares
let service = Service::new(handler);

// 4. Finally just run server using the service already created
// 3. Finally just run server using the service already created
let addr = ([127, 0, 0, 1], 8787).into();
let server = Server::bind(&addr).serve(service);

Expand All @@ -129,7 +128,7 @@ async fn main() -> Result {

To run the example just type:

```
```sh
cargo run --example server
```

Expand Down
Loading

0 comments on commit c0aa9cf

Please sign in to comment.