Skip to content

Commit

Permalink
fix: send headers on every response
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrahman1s committed Jul 15, 2022
1 parent 1df9ba9 commit 3d8021e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
12 changes: 9 additions & 3 deletions src/middlewares/ratelimit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type RateLimiter =
Limiter<String, DefaultKeyedStateStore<String>, DefaultClock, StateInformationMiddleware>;

pub async fn ratelimit<B>(
mut req: Request<B>,
req: Request<B>,
next: Next<B>,
limiter: Arc<RateLimiter>,
) -> Result<Response, Error> {
Expand Down Expand Up @@ -59,11 +59,17 @@ pub async fn ratelimit<B>(

if info.retry_after > 0 {
log::info!("IP: {} has executed the rate limit", key);
req.extensions_mut().insert(info);
return Err(Error::RateLimited(info));
}

Ok(next.run(req).await)
let mut res = next.run(req).await;
let headers = res.headers_mut();

headers.insert("X-RateLimit-Remaining", info.remaining.into());
headers.insert("X-RateLimit-Limit", info.limit.into());
headers.insert("Retry-After", info.retry_after.into());

Ok(res)
}

#[macro_export]
Expand Down
5 changes: 3 additions & 2 deletions src/utils/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::fmt::Debug;

quick_error! {
#[derive(Debug, Serialize, OpgModel)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Error {
RateLimited(info: RateLimitInfo) {
from(RateLimitInfo)
Expand Down Expand Up @@ -90,11 +91,11 @@ impl IntoResponse for Error {
};

let mut headers = HeaderMap::new();
let mut body = serde_json::json!({ "type": self });
let mut body = serde_json::json!(self);
let msg = self.to_string();

if msg.contains(' ') {
body["message"] = serde_json::json!(msg);
body["message"] = msg.into();
}

if let Error::RateLimited(info) = self {
Expand Down

0 comments on commit 3d8021e

Please sign in to comment.