Gateway 聚合文档使用v3接口是无法访问

内容纲要

swagger中使用V3时,获取到docs得到的接口为v3/api-docs接口,但是此接口并没有将请求的前置加上,所有直接使用swagger的时候是无法访问的

原因分析

主要原因为在v3/api-docs返回的JSON对象中,servers返回的url中只存在ip(域名)+端口的连接,但是请求前缀并没有加上,**请求会缺失basePath(如果使用服务名动态路由的话,则实际缺失的是对应微服务的applicationName)**

我们需要的则应该是把basePath加上的,如下图

修改防范

V3的接口地址在OpenApiControllerWebMvc类中,我们可以采用Spring Aop 的方式去拦截此方法,将获取到的servers返回的url添加上baseUrl,代码如下
/**
 * @author Clay
 * @date 2023-05-07
 */
@Slf4j
@Aspect
@Component
public class SwaggerAspect {

    @SneakyThrows
    @Around("execution(* springfox.documentation.oas.web.OpenApiControllerWebMvc.getDocumentation(..))")
    public Object around(ProceedingJoinPoint point) {
        ResponseEntity<Json> proceed = (ResponseEntity<Json>) point.proceed();
        String value = proceed.getBody().value();
        JSONObject object = JSON.parseObject(value);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        JSONArray servers = object.getJSONArray("servers");
        String basePath = null;
        for (int i = 0; i < servers.size(); i++) {
            JSONObject server = servers.getJSONObject(i);
            String path = server.getString("url");
            if (null == basePath){
                UriComponents uriComponents = HostNameProvider.componentsFrom(request, path);
                basePath = StringUtils.isEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath();
            }
            server.put("url", path + basePath);
        }
        object.put("basePath",basePath);
        return new ResponseEntity<>(object.toString(), HttpStatus.OK);
    }
}
THE END
分享
二维码
< <上一篇
下一篇>>