pub struct Pipeline<T>where
T: NewMiddlewareChain,{ /* private fields */ }
Expand description
When using middleware, one or more Middleware
are combined to form a Pipeline
.
Middleware
are invoked strictly in the order they’re added to the Pipeline
.
At Request
dispatch time, the Middleware
are created from the NewMiddleware
values given
to the PipelineBuilder
, and combined with a Handler
created from the NewHandler
provided
to Pipeline::call
. These Middleware
and Handler
values are used for a single Request
.
Examples
#[derive(StateData)]
struct MiddlewareData {
vec: Vec<i32>,
}
#[derive(NewMiddleware, Copy, Clone)]
struct MiddlewareOne;
impl Middleware for MiddlewareOne {
// Implementation elided.
// Appends `1` to `MiddlewareData.vec`
}
#[derive(NewMiddleware, Copy, Clone)]
struct MiddlewareTwo;
impl Middleware for MiddlewareTwo {
// Implementation elided.
// Appends `2` to `MiddlewareData.vec`
}
#[derive(NewMiddleware, Copy, Clone)]
struct MiddlewareThree;
impl Middleware for MiddlewareThree {
// Implementation elided.
// Appends `3` to `MiddlewareData.vec`
}
fn handler(state: State) -> (State, Response<Body>) {
let body = {
let data = state.borrow::<MiddlewareData>();
format!("{:?}", data.vec)
};
let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, body);
(state, res)
}
fn main() {
let (chain, pipelines) = single_pipeline(
new_pipeline()
.add(MiddlewareOne)
.add(MiddlewareTwo)
.add(MiddlewareThree)
.build(),
);
let router = build_router(chain, pipelines, |route| {
route.get("/").to(handler);
});
let test_server = TestServer::new(router).unwrap();
let response = test_server
.client()
.get("http://example.com/")
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.read_utf8_body().unwrap(), "[1, 2, 3]");
}