From dd72f756953bb8cccaba445118f94a70aeda6aea Mon Sep 17 00:00:00 2001 From: Kim Daehyeon Date: Sun, 25 Feb 2024 04:53:22 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20request=20body=20=ED=98=95=EC=8B=9D=20J?= =?UTF-8?q?son=EC=9C=BC=EB=A1=9C=20=EB=B3=80=ED=99=98=20-=20#77?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - slack에서의 가독성 --- .../bagel/aspect/RateLimitAspect.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/mjulikelion/bagel/aspect/RateLimitAspect.java b/src/main/java/org/mjulikelion/bagel/aspect/RateLimitAspect.java index b3381ae..04f0b8a 100644 --- a/src/main/java/org/mjulikelion/bagel/aspect/RateLimitAspect.java +++ b/src/main/java/org/mjulikelion/bagel/aspect/RateLimitAspect.java @@ -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; @@ -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); @@ -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); }