Comments (4)
I've tried this:
use actix_http::header::CONTENT_TYPE;
use actix_session::SessionExt;
use actix_web::{
body::{self, MessageBody},
dev::{ServiceRequest, ServiceResponse},
http::{
header::{HeaderValue, CACHE_CONTROL},
Method, StatusCode,
},
Error, HttpResponse,
};
use actix_web_lab::middleware::Next;
pub async fn cache_middleware(
req: ServiceRequest,
next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, Error> {
let key = format!("{}{}", req.path(), req.query_string());
let session = req.get_session();
if let Ok(cached_response) = session.get::<String>(&key) {
//println!("{:?}", cached_response);
if cached_response.is_some() {
let res = HttpResponse::new(StatusCode::OK).set_body(cached_response.unwrap());
let mut res = ServiceResponse::new(req.request().to_owned(), res);
res.headers_mut()
.append(CONTENT_TYPE, HeaderValue::from_static("application/json"));
res.headers_mut()
.append(CACHE_CONTROL, HeaderValue::from_static("max-age=86400"));
return Ok(res);
}
}
// Call the next service
let res = next.call(req).await?;
// deconstruct response into parts
let (req, res) = res.into_parts();
let (res, body) = res.into_parts();
// Convert body to Bytes
let body = body::to_bytes(body).await.ok().unwrap();
// Use bytes directly for caching instead of converting to a String
let res_body_enc = std::str::from_utf8(&body).unwrap();
let res = res.set_body(res_body_enc.to_owned());
let mut res = ServiceResponse::new(req.to_owned(), res);
println!("{}, {}", req.method(), res.status());
if req.method() == Method::GET && StatusCode::is_success(&res.status()) {
println!("caching");
res.headers_mut()
.append(CACHE_CONTROL, HeaderValue::from_static("max-age=86400"));
if let Err(e) = session.insert(key, res_body_enc) {
println!("cache insert error: {}", e);
}
} else {
println!("not caching");
}
Ok(res)
}
it's working fine but i'm not sure if it can be optimized to improve efficiency and performance
from examples.
PR welcome where comments on specifics can be made.
from examples.
PR welcome where comments on specifics can be made.
Ok, but I’ll have to fix the problem when redis is not running, it will always return status 500 when session.get() or session.set() is called, the error catch block is not working.
and I’ll have to implement header Cache-Control: no-cache directive in case I want to skip cache.
from examples.
PR welcome where comments on specifics can be made.
Ready for review #630
from examples.
Related Issues (20)
- Redis example with pooled connection HOT 3
- Streaming responses (from an AsyncWrite) HOT 3
- Read request body Middleware panics when json Body is sent HOT 8
- About protobuf HOT 1
- actix_cors is always returing 404 on OPTIONS requests
- identity logout does not have effect
- The basic/todo app breaks with 405 (method not allowed) after create/update action applied on an item
- Please add rate-limit example HOT 2
- auth/simple-auth-server panics when default `SECRET_KEY` is used to instantiate a `actix_web::cookie::Key` instance
- Executing send_message from Actix Websocket Chat example HOT 1
- example for Mysql client library (MySql database driver) HOT 1
- No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. HOT 1
- Expand postgres example to include querying/fetching all HOT 3
- webauthn passkey example
- Server-sent-events example not working correctly
- Having examples use actix_web_lab is confusing HOT 2
- please update rustls example to 0.22.0 HOT 2
- Improve Test Documentation
- Tagging clients in SSE
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from examples.