Skip to content

Commit 37a8231

Browse files
committed
feat: improve redirect rule parsing and validation
feat: add regex support and enforce 301/302 redirects
1 parent f48524b commit 37a8231

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

src/main/java/org/example/server/RedirectRule.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.example.server;
22

3+
import java.util.Objects;
34
import java.util.regex.Pattern;
45

56
public final class RedirectRule {
@@ -8,8 +9,11 @@ public final class RedirectRule {
89
private final int statusCode;
910

1011
public RedirectRule(Pattern sourcePattern, String targetUrl, int statusCode) {
11-
this.sourcePattern = sourcePattern;
12-
this.targetUrl = targetUrl;
12+
this.sourcePattern = Objects.requireNonNull(sourcePattern, "sourcePattern");
13+
this.targetUrl = Objects.requireNonNull(targetUrl, "targetUrl");
14+
if (statusCode != 301 && statusCode != 302) {
15+
throw new IllegalArgumentException("statusCode must be 301 or 302");
16+
}
1317
this.statusCode = statusCode;
1418
}
1519

@@ -30,3 +34,4 @@ public String toString() {
3034
'}';
3135
}
3236
}
37+

src/main/java/org/example/server/RedirectRulesLoader.java

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,30 @@
33
import java.util.regex.Pattern;
44

55
public final class RedirectRulesLoader {
6+
private static final String REGEX_PREFIX = "regex:";
7+
68
private RedirectRulesLoader() {}
79

810
public static Pattern compileSourcePattern(String sourcePath) {
911
if (sourcePath == null || sourcePath.isBlank()) {
1012
throw new IllegalArgumentException("sourcePath must not be blank");
1113
}
1214

15+
String trimmed = sourcePath.trim();
16+
17+
if (trimmed.startsWith(REGEX_PREFIX)) {
18+
String rawRegex = trimmed.substring(REGEX_PREFIX.length());
19+
if (rawRegex.isBlank()) {
20+
throw new IllegalArgumentException("regex sourcePath must not be blank");
21+
}
22+
return Pattern.compile(rawRegex);
23+
}
24+
1325
String regex;
14-
if (sourcePath.contains("*")) {
15-
regex = wildcardToRegex(sourcePath);
26+
if (trimmed.contains("*")) {
27+
regex = wildcardToRegex(trimmed);
1628
} else {
17-
regex = Pattern.quote(sourcePath);
29+
regex = Pattern.quote(trimmed);
1830
}
1931
return Pattern.compile("^" + regex + "$");
2032
}
@@ -32,3 +44,4 @@ private static String wildcardToRegex(String wildcard) {
3244
return sb.toString();
3345
}
3446
}
47+

0 commit comments

Comments
 (0)