Skip to content

Commit aedeeb2

Browse files
committed
Add CORS headers to actual responses and fix premature response flush
- Remove early ctx.writeAndFlush(response) to avoid sending response before headers are finalized - Add dynamic CORS headers (Access-Control-Allow-Origin, Vary, Allow-Credentials) to normal responses - Respect request Origin header and configuration for allowed origins and credentials
1 parent 975e34e commit aedeeb2

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/main/java/org/tinystruct/handler/HttpRequestHandler.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,6 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest original)
9999
return;
100100
}
101101

102-
ctx.writeAndFlush(response);
103-
104102
// Decide whether to close the connection or not.
105103
boolean keepAlive = HttpUtil.isKeepAlive(original);
106104
boolean ssl = Boolean.parseBoolean(configuration.getOrDefault("ssl.enabled", "false"));
@@ -126,6 +124,18 @@ private void service(final ChannelHandlerContext ctx, final Request<FullHttpRequ
126124

127125
HttpResponseStatus status = OK;
128126
ResponseBuilder response = new ResponseBuilder(new DefaultFullHttpResponse(HTTP_1_1, status), ctx);
127+
128+
// Set CORS headers on the actual response
129+
Object origin = request.headers().get(Header.ORIGIN);
130+
String allowOrigin = configuration.getOrDefault("cors.allowed.origins", origin != null ? origin.toString() : "*");
131+
response.addHeader(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.toString(), allowOrigin);
132+
if (origin != null) {
133+
response.addHeader(HttpHeaderNames.VARY.toString(), "Origin");
134+
}
135+
if ("true".equalsIgnoreCase(configuration.get("cors.allow.credentials"))) {
136+
response.addHeader(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS.toString(), "true");
137+
}
138+
129139
String host = request.headers().get(Header.HOST).toString();
130140
Object message;
131141
try {

0 commit comments

Comments
 (0)