Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ members = [
"json/json",
"json/jsonrpc",
"middleware/encrypted-payloads",
"middleware/http-response",
"middleware/http-to-https",
"middleware/rate-limit",
"middleware/request-extensions",
Expand Down
5 changes: 3 additions & 2 deletions cache/redis/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::env;

use actix_web::middleware::{Next, from_fn};
use actix_web::{
App, Error, HttpResponse, HttpServer, Responder,
body::{self, MessageBody},
Expand All @@ -9,7 +8,9 @@ use actix_web::{
Method, StatusCode,
header::{CACHE_CONTROL, CACHE_STATUS, CONTENT_TYPE, CacheDirective, HeaderValue},
},
middleware, web,
middleware,
middleware::{Next, from_fn},
web,
};
use redis::{Client as RedisClient, Commands, RedisError};

Expand Down
12 changes: 12 additions & 0 deletions middleware/http-response/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "middleware-return-http-response"
version = "1.0.0"
edition.workspace = true
rust-version.workspace = true

[dependencies]
actix-web.workspace = true
env_logger.workspace = true
futures-util.workspace = true
log.workspace = true
serde.workspace = true
35 changes: 35 additions & 0 deletions middleware/http-response/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
## Middleware : Return HttpResponse from Middleware

```rs
cd middleware-return-httpresponse
cargo run
# Started http server: 127.0.0.1:8080
```

## What is this?

A Middleware example which returning HttpResponse.

## How to test

### success case
```sh
curl http://127.0.0.1:8080/ -H 'Authorization:ok' | json_pp -json_opt pretty,canonical
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 42 100 42 0 0 42000 0 --:--:-- --:--:-- --:--:-- 42000
{
"data" : "Hello this is success response!"
}
```

### failed case
```sh
curl http://127.0.0.1:8080/ | json_pp -json_opt pretty,canonical
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 102 100 102 0 0 99k 0 --:--:-- --:--:-- --:--:-- 99k
{
"data" : "Hello this is default error message! you need to set Authorization header to get thru this."
}
```
36 changes: 36 additions & 0 deletions middleware/http-response/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use actix_web::{App, HttpResponse, HttpServer, web};

mod simple;

// You can move this struct to a separate file.
// this struct below just for example.
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpData {
pub data: String,
}
// this implementation is optional
impl Default for HttpData {
fn default() -> Self {
Self {
data: "Hello this is success response!".to_string(),
}
}
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(|| {
App::new().wrap(simple::ReturnHttpResponse).service(
web::resource("/").to(|| async { HttpResponse::Ok().json(HttpData::default()) }),
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
87 changes: 87 additions & 0 deletions middleware/http-response/src/simple.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
use std::{
future::{Ready, ready},
rc::Rc,
};

use actix_web::{
Error, HttpResponseBuilder,
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
http::{StatusCode, header},
};
use futures_util::future::LocalBoxFuture;
// You can move this struct to a separate file.
// this struct below just for example.
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpData {
pub data: String,
}
// this implementation is optional
impl Default for HttpData {
fn default() -> Self {
Self {
data: "Hello this is default error message! you need to set Authorization header to get thru this.".to_string(),
}
}
}

pub struct ReturnHttpResponse;

impl<S: 'static> Transform<S, ServiceRequest> for ReturnHttpResponse
where
S: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
S::Future: 'static,
{
type Response = ServiceResponse;
type Error = Error;
type InitError = ();
type Transform = AuthMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;

fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(AuthMiddleware {
service: Rc::new(service),
}))
}
}

pub struct AuthMiddleware<S> {
// This is special: We need this to avoid lifetime issues.
service: Rc<S>,
}

impl<S> Service<ServiceRequest> for AuthMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse, Error = Error> + 'static,
S::Future: 'static,
{
type Response = ServiceResponse;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

dev::forward_ready!(service);

fn call(&self, req: ServiceRequest) -> Self::Future {
let svc = self.service.clone();

Box::pin(async move {
let headers = req.headers();
let _ = match headers.get("Authorization") {
Some(e) => e,
None => {
let new_response = HttpResponseBuilder::new(StatusCode::BAD_REQUEST)
.insert_header((header::CONTENT_TYPE, "application/json"))
.json(HttpData::default());
return Ok(ServiceResponse::new(
req.request().to_owned(), /* or req.request().clone() */
new_response,
));
}
};

let res = svc.call(req).await?;
Ok(res)
})
}
}