Skip to content

Commit bfb240d

Browse files
committed
Add support for URI path prefix modification
Fixes spring-projectsgh-945
1 parent dfa9496 commit bfb240d

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

spring-restdocs-core/src/main/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessor.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ public class UriModifyingOperationPreprocessor implements OperationPreprocessor
6666

6767
private String port;
6868

69+
private String pathPrefix;
70+
6971
/**
7072
* Modifies the URI to use the given {@code scheme}. {@code null}, the default, will
7173
* leave the scheme unchanged.
@@ -99,6 +101,17 @@ public UriModifyingOperationPreprocessor port(int port) {
99101
return port(Integer.toString(port));
100102
}
101103

104+
/**
105+
* Modifies the URI to add the given path prefix.
106+
* @param pathPrefix the path prefix to add
107+
* @return {@code this}
108+
*/
109+
public UriModifyingOperationPreprocessor pathPrefix(String pathPrefix) {
110+
this.pathPrefix = pathPrefix;
111+
this.contentModifier.setPathPrefix(pathPrefix);
112+
return this;
113+
}
114+
102115
/**
103116
* Removes the port from the URI.
104117
* @return {@code this}
@@ -130,6 +143,10 @@ public OperationRequest preprocess(OperationRequest request) {
130143
uriBuilder.port(null);
131144
}
132145
}
146+
if (this.pathPrefix != null) {
147+
String rawPath = request.getUri().getRawPath();
148+
uriBuilder.replacePath(this.pathPrefix + ((rawPath != null) ? rawPath : ""));
149+
}
133150
URI modifiedUri = uriBuilder.build(true).toUri();
134151
HttpHeaders modifiedHeaders = modify(request.getHeaders());
135152
modifiedHeaders.set(HttpHeaders.HOST,
@@ -177,6 +194,8 @@ private static final class UriModifyingContentModifier implements ContentModifie
177194

178195
private String port;
179196

197+
private String pathPrefix;
198+
180199
private void setScheme(String scheme) {
181200
this.scheme = scheme;
182201
}
@@ -189,6 +208,10 @@ private void setPort(String port) {
189208
this.port = port;
190209
}
191210

211+
private void setPathPrefix(String pathPrefix) {
212+
this.pathPrefix = pathPrefix;
213+
}
214+
192215
@Override
193216
public byte[] modifyContent(byte[] content, MediaType contentType) {
194217
String input;
@@ -204,7 +227,8 @@ public byte[] modifyContent(byte[] content, MediaType contentType) {
204227

205228
private String modify(String input) {
206229
List<String> replacements = Arrays.asList(this.scheme, this.host,
207-
StringUtils.hasText(this.port) ? ":" + this.port : this.port);
230+
StringUtils.hasText(this.port) ? ":" + this.port : this.port,
231+
this.pathPrefix);
208232

209233
int previous = 0;
210234

0 commit comments

Comments
 (0)