Skip to content

Commit d326115

Browse files
committed
feat: Dispatch request body parsing by Content-Type subtype
1 parent 777d7a5 commit d326115

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

src/main/java/com/retailsvc/http/internal/RequestPreparationFilter.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ public final class RequestPreparationFilter extends Filter {
2727
private final Router router;
2828
private final Validator validator;
2929
private final JsonMapper jsonMapper;
30+
private final FormUrlEncodedParser formParser = new FormUrlEncodedParser();
31+
private final TextPlainParser textParser = new TextPlainParser();
3032

3133
public RequestPreparationFilter(
3234
Spec spec, Router router, Validator validator, JsonMapper jsonMapper) {
@@ -140,18 +142,21 @@ private Object validateAndParseBody(HttpExchange exchange, Operation op, byte[]
140142
}
141143
return null;
142144
}
143-
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
144-
if (contentType == null) {
145-
contentType = "application/json";
146-
}
147-
contentType = contentType.split(";", 2)[0].trim();
148-
MediaType mt = rb.get().content().get(contentType);
145+
String header = exchange.getRequestHeaders().getFirst("Content-Type");
146+
String subtype = ContentTypeHeader.subtype(header);
147+
MediaType mt = rb.get().content().get(subtype);
149148
if (mt == null) {
150149
throw new ValidationException(
151150
new ValidationError(
152-
"/body", "content-type", "unsupported content type: " + contentType, null));
151+
"/body", "content-type", "unsupported content type: " + subtype, null));
153152
}
154-
Object parsed = jsonMapper.mapFrom(body);
153+
Object parsed =
154+
switch (subtype) {
155+
case "application/x-www-form-urlencoded" ->
156+
formParser.parseAndCoerce(body, header, mt.schema());
157+
case "text/plain" -> textParser.parse(body, header);
158+
default -> jsonMapper.mapFrom(body);
159+
};
155160
validator.validate(parsed, mt.schema(), "");
156161
return parsed;
157162
}

0 commit comments

Comments
 (0)