kotlin - 在 Spring Rest Docs 中添加基本 url 的路径?
问题描述
我有以下配置与 Rest Docs 一起使用:
webTestClient = buildWebClient().mutate()
.filter(documentationConfiguration(restDocumentation))
.baseUrl("https://api.my-domain.com/")
.build()
在我的情况下,我对我的服务使用路径前缀 -service/foo
因为我使用 k8s 入口并且我的服务是在路径偏移上提供的。
有没有办法在不修改生产代码的情况下插入这样的前缀?
相关文档片段:
解决方案
要记录另一个 URI 而不是生成文档所调用的 URI,您必须编写自己的OperationPreprocessor
. 有一些预定义的类似Preprocessors.modifyUris
,但它不允许修改请求路径。
检查下面的 webTestClient 配置和URIUpdaterOperationRequest
类。代码在 GitHub 上可用:https ://github.com/Query-Interface/SO-Answers/blob/master/java/spring/rest-docs-modify-uripath/src/test/java/com/example/demo/ DemoApplicationTests.java
public void init() throws Exception {
final URIUpdaterPreprocessor preprocessor = new URIUpdaterPreprocessor();
webTestClient = webTestClient.mutate()
.filter((documentationConfiguration(this.restDocumentation)
.operationPreprocessors()
.withRequestDefaults(preprocessor)
.withResponseDefaults(prettyPrint()))
)
.build();
}
private static final class URIUpdaterPreprocessor
implements OperationPreprocessor {
@Override
public OperationRequest preprocess(OperationRequest request) {
return new URIUpdaterOperationRequest(request);
}
@Override
public OperationResponse preprocess(OperationResponse response) {
return response;
}
}
private static final class URIUpdaterOperationRequest
implements OperationRequest {
private OperationRequest delegate;
public URIUpdaterOperationRequest(OperationRequest request) {
delegate = request;
}
public byte[] getContent() {
return delegate.getContent();
}
public String getContentAsString() {
return delegate.getContentAsString();
}
public HttpHeaders getHeaders() {
return delegate.getHeaders();
}
public HttpMethod getMethod() {
return delegate.getMethod();
}
public Parameters getParameters() {
return delegate.getParameters();
}
public Collection<OperationRequestPart> getParts() {
return delegate.getParts();
}
public URI getUri() {
URI sourceUri = delegate.getUri();
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(sourceUri);
return builder
.host(sourceUri.getHost())
.replacePath("/service/foo"+sourceUri.getPath())
.build().toUri();
}
public Collection<RequestCookie> getCookies() {
return delegate.getCookies();
}
}
我认为另一种可能性是更新 mustache 模板,以便在所有请求路径引用之前添加前缀。默认模板位于 github 上。
推荐阅读
- python - 将 jQuery 添加到 Django 管理页面以进行下拉选择以启用/禁用它
- ssh - 了解 Tar 命令在远程服务器上归档和压缩文件
- android - 如何使用 Kotlin Android 在 Retrofit 中传递 body?
- database - laravel 中查询的意外结果
- java - 在 Heroku 上部署 Spring Boot 时出现 Google api 重定向问题
- arrays - SC2207 来自 subshell 的 Bash 数组分配未按预期拆分
- python - 为什么 pip 不安装最新版本的软件包,即使 PyPI 上有更新版本?
- c# - 如何更改 selenium 远程 Web 驱动程序中的用户代理
- jquery - jquery 用于在 woocommerce 中显示每个下拉列表
- php - 目标空白不适用于 wordpress