From bfb240db6d8d43e46460d5717b1632faa0b8d221 Mon Sep 17 00:00:00 2001 From: dae won Date: Fri, 27 Dec 2024 20:16:09 +0900 Subject: [PATCH] Add support for URI path prefix modification Fixes gh-945 --- .../UriModifyingOperationPreprocessor.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java index b36d9715..19866663 100644 --- a/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java +++ b/spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java @@ -66,6 +66,8 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor private String port; + private String pathPrefix; + /** * Modifies the URI to use the given {@code scheme}. {@code null}, the default, will * leave the scheme unchanged. @@ -99,6 +101,17 @@ public UriModifyingOperationPreprocessor port(int port) { return port(Integer.toString(port)); } + /** + * Modifies the URI to add the given path prefix. + * @param pathPrefix the path prefix to add + * @return {@code this} + */ + public UriModifyingOperationPreprocessor pathPrefix(String pathPrefix) { + this.pathPrefix = pathPrefix; + this.contentModifier.setPathPrefix(pathPrefix); + return this; + } + /** * Removes the port from the URI. * @return {@code this} @@ -130,6 +143,10 @@ public OperationRequest preprocess(OperationRequest request) { uriBuilder.port(null); } } + if (this.pathPrefix != null) { + String rawPath = request.getUri().getRawPath(); + uriBuilder.replacePath(this.pathPrefix + ((rawPath != null) ? rawPath : "")); + } URI modifiedUri = uriBuilder.build(true).toUri(); HttpHeaders modifiedHeaders = modify(request.getHeaders()); modifiedHeaders.set(HttpHeaders.HOST, @@ -177,6 +194,8 @@ private static final class UriModifyingContentModifier implements ContentModifie private String port; + private String pathPrefix; + private void setScheme(String scheme) { this.scheme = scheme; } @@ -189,6 +208,10 @@ private void setPort(String port) { this.port = port; } + private void setPathPrefix(String pathPrefix) { + this.pathPrefix = pathPrefix; + } + @Override public byte[] modifyContent(byte[] content, MediaType contentType) { String input; @@ -204,7 +227,8 @@ public byte[] modifyContent(byte[] content, MediaType contentType) { private String modify(String input) { List replacements = Arrays.asList(this.scheme, this.host, - StringUtils.hasText(this.port) ? ":" + this.port : this.port); + StringUtils.hasText(this.port) ? ":" + this.port : this.port, + this.pathPrefix); int previous = 0;