feat: mock功能

This commit is contained in:
2026-01-29 13:19:19 +08:00
parent 4ab79d3afa
commit ff6f8aa303
20 changed files with 909 additions and 9 deletions

View File

@@ -0,0 +1,100 @@
package org.nl.core.config;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.nl.tool.mock.core.config.MockConfigProperties;
import org.nl.tool.mock.core.handle.MockService;
import org.nl.tool.mock.modular.mockconfig.entity.MockConfig;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Optional;
/**
* Mock拦截器
* 用于拦截入站HTTP请求根据Mock配置返回Mock数据
* 实现HandlerInterceptor接口在Controller方法执行前进行拦截
*
* 工作流程:
* 1. 检查全局Mock开关是否启用
* 2. 提取请求路径和HTTP方法
* 3. 查询Mock配置优先从缓存获取
* 4. 如果Mock配置存在且启用直接返回Mock数据
* 5. 否则继续执行Controller方法
*/
@Component
@Slf4j
public class MockInterceptor implements HandlerInterceptor {
private final MockService mockService;
private final MockConfigProperties properties;
/**
* 构造函数,注入依赖
*
* @param mockService Mock服务
* @param properties Mock配置属性
*/
public MockInterceptor(MockService mockService, MockConfigProperties properties) {
this.mockService = mockService;
this.properties = properties;
}
/**
* 在Controller方法执行前拦截请求
*
* @param request HTTP请求
* @param response HTTP响应
* @param handler 处理器
* @return true表示继续执行Controllerfalse表示拦截并返回Mock数据
* @throws Exception 处理过程中的异常
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
// 检查全局Mock开关
if (!properties.isEnabled()) {
log.debug("Mock functionality is globally disabled, continuing to controller");
return true; // Mock功能禁用继续执行Controller
}
// todo: 检测白名单
// 提取请求路径和方法
String path = request.getRequestURI();
String method = request.getMethod();
log.debug("Intercepting request: {} {}", method, path);
// 查询Mock配置
Optional<MockConfig> mockConfig = mockService.getMockConfig(path, method);
// 检查Mock配置是否存在且启用
if (mockConfig.isPresent() && mockConfig.get().getIsEnabled()) {
MockConfig config = mockConfig.get();
// 设置响应头
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.OK.value());
// 写入Mock响应数据
response.getWriter().write(config.getResponseJson());
response.getWriter().flush();
// 记录Mock使用日志
if (properties.isLogMockUsage()) {
log.info("Mock response returned for {} {} (config id: {})",
method, path, config.getId());
}
return false; // 拦截请求不继续执行Controller
}
// Mock配置不存在或未启用继续执行Controller
log.debug("No active mock config found for {} {}, continuing to controller", method, path);
return true;
}
}