Skip to content

Commit

Permalink
feat: request body 형식 Json으로 변환 - #77
Browse files Browse the repository at this point in the history
- slack에서의 가독성
  • Loading branch information
Dh3356 committed Feb 24, 2024
1 parent 9473621 commit dd72f75
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/main/java/org/mjulikelion/bagel/aspect/RateLimitAspect.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import static org.mjulikelion.bagel.errorcode.ErrorCode.RATE_LIMIT_ERROR;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;
import io.github.bucket4j.local.LocalBucketBuilder;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.Map;
Expand Down Expand Up @@ -53,7 +55,7 @@ public Object rateLimitAdvice(ProceedingJoinPoint joinPoint, RateLimit rateLimit
.build());

if (!bucket.tryConsume(1)) {
String requestBody = getRequestBodyAsString(joinPoint);
String requestBody = getRequestBodyAsJsonString(joinPoint);
this.sendSlackMessage(ipAddress, request.getRequestURL().toString(), requestBody);
this.logRateLimitExceeded(ipAddress, request.getRequestURL().toString(), requestBody);
throw new RateLimitException(RATE_LIMIT_ERROR);
Expand All @@ -72,16 +74,30 @@ private HttpServletRequest getRequest(ProceedingJoinPoint joinPoint) {
return (attributes != null) ? attributes.getRequest() : null;
}

private String getRequestBodyAsString(ProceedingJoinPoint joinPoint) throws UnsupportedEncodingException {
private String getRequestBodyAsJsonString(ProceedingJoinPoint joinPoint) throws UnsupportedEncodingException {
HttpServletRequest request = getRequest(joinPoint);
if (request instanceof ContentCachingRequestWrapper wrapper) {
byte[] requestBody = wrapper.getContentAsByteArray();
String requestBodyString = new String(requestBody, request.getCharacterEncoding());
return requestBodyString.isBlank() ? "No request body" : requestBodyString;

if (isJsonString(requestBodyString)) {
return requestBodyString;
} else {
return "Not a valid JSON format";
}
}
return null;
}

private boolean isJsonString(String value) {
try {
new ObjectMapper().readTree(value);
return true;
} catch (IOException e) {
return false;
}
}

private void logRateLimitExceeded(String ipAddress, String requestUrl, String requestBody) {
log.warn("Rate limit exceeded for IP: {} and URL: {}, request body: {}", ipAddress, requestUrl, requestBody);
}
Expand Down

0 comments on commit dd72f75

Please sign in to comment.