1
0
mirror of https://github.com/actix/examples synced 2025-06-28 09:50:36 +02:00

restructure folders

This commit is contained in:
Rob Ede
2022-02-18 02:01:48 +00:00
parent 4d8573c3fe
commit cc3d356209
201 changed files with 52 additions and 49 deletions

View File

@ -0,0 +1,9 @@
[package]
name = "middleware-ext-mut"
version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = "4.0.0-rc.1"
log = "0.4"
env_logger = "0.9"

View File

@ -0,0 +1,18 @@
# middleware examples
This example showcases a middleware that adds and retrieves request-local data. See also the [Middleware guide](https://actix.rs/docs/middleware/).
## Usage
```bash
cd basics/middleware-ext-mut
cargo run
# Started http server: 127.0.0.1:8080
```
Look in `src/add_msg.rs` to see how it works.
## Routes
- [GET /on](http://localhost:8080/on) - `200 OK` with "hello from middleware" body and console log showing the request passed through the middleware
- [GET /off](http://localhost:8080/off) - `500 Internal Server Error` with "no message found" body and console log showing the request passed through the middleware

View File

@ -0,0 +1,77 @@
use std::{
future::{ready, Ready},
task::{Context, Poll},
};
use actix_web::Error;
use actix_web::{
dev::{Service, ServiceRequest, ServiceResponse, Transform},
HttpMessage,
};
#[derive(Debug, Clone)]
pub struct Msg(pub String);
#[doc(hidden)]
pub struct AddMsgService<S> {
service: S,
enabled: bool,
}
impl<S, B> Service<ServiceRequest> for AddMsgService<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = S::Future;
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(ctx)
}
fn call(&self, req: ServiceRequest) -> Self::Future {
log::info!("request is passing through the AddMsg middleware");
if self.enabled {
// insert data into extensions if enabled
req.extensions_mut()
.insert(Msg("Hello from Middleware!".to_owned()));
}
self.service.call(req)
}
}
#[derive(Clone, Debug)]
pub struct AddMsg {
enabled: bool,
}
impl AddMsg {
pub fn enabled() -> Self {
Self { enabled: true }
}
pub fn disabled() -> Self {
Self { enabled: false }
}
}
impl<S, B> Transform<S, ServiceRequest> for AddMsg
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
type Transform = AddMsgService<S>;
type InitError = ();
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(AddMsgService {
service,
enabled: self.enabled,
}))
}
}

View File

@ -0,0 +1,36 @@
use std::{env, io};
use actix_web::{
middleware,
web::{self, ReqData},
App, HttpResponse, HttpServer,
};
mod add_msg;
use crate::add_msg::{AddMsg, Msg};
// wrap route in our middleware factory
async fn index(msg: Option<ReqData<Msg>>) -> HttpResponse {
if let Some(msg_data) = msg {
let Msg(message) = msg_data.into_inner();
HttpResponse::Ok().body(message)
} else {
HttpResponse::InternalServerError().body("No message found.")
}
}
#[actix_web::main]
async fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "info");
env_logger::init();
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(web::resource("/on").wrap(AddMsg::enabled()).to(index))
.service(web::resource("/off").wrap(AddMsg::disabled()).to(index))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}