Skip to content

Commit

Permalink
Add CORS support; turn down logging on methods (#236)
Browse files Browse the repository at this point in the history
* Add CORS support
* Only log on GET, METHOD, and OPTIONS
  • Loading branch information
ksclarke authored Jan 19, 2025
1 parent a37095d commit 0a2e8f0
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/main/java/info/freelibrary/iiif/webrepl/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -153,13 +153,13 @@ static class JPv3Handler implements Handler {
private static final byte[] EMPTY_BODY = {};

/** The response headers that are returned. */
private static final List<Header> HTML_CONTENT_TYPE = List.of(new Header(CONTENT_TYPE, "text/html"));
private static final List<Header> HTML_CONTENT_TYPE = getHeaders(new Header(CONTENT_TYPE, "text/html"));

/** A hard-coded snippet that will return the result of the supplied code snippet. */
private static final String MAIN_METHOD = "Jpv3Snippet.main(new String[]{});";

/** The response headers that are returned for plain text responses. */
private static final List<Header> TEXT_CONTENT_TYPE = List.of(new Header(CONTENT_TYPE, "text/plain"));
private static final List<Header> TEXT_CONTENT_TYPE = getHeaders(new Header(CONTENT_TYPE, "text/plain"));

/** A cached {@code WebResource}. */
private final byte[] myHTML;
Expand Down Expand Up @@ -201,10 +201,10 @@ public void handle(final Request aRequest, final Consumer<Response> aCallback) {
final String uri = aRequest.uri();
final Response response;

System.err.println(aRequest.method() + SPACE + uri);

switch (aRequest.method()) {
case "POST" -> {
System.err.println(aRequest.method() + SPACE + uri);

if (uri.endsWith("submit") || uri.endsWith("submit/")) {
final StringBuilder submission = new StringBuilder();

Expand Down Expand Up @@ -261,6 +261,8 @@ public void handle(final Request aRequest, final Consumer<Response> aCallback) {
}
}
case "GET" -> {
System.err.println(aRequest.method() + SPACE + uri);

if (uri.endsWith("editor") || uri.endsWith("editor/")) {
response = getResponse(OK, HTML_CONTENT_TYPE, myHTML);
} else {
Expand Down Expand Up @@ -378,5 +380,18 @@ private Response getResponse(final info.freelibrary.iiif.webrepl.Status aEnum, f
final byte[] aBody) {
return new Response(aEnum.getCode(), aEnum.getMessage(), aHeaderList, aBody);
}

/**
* Creates a list of Header(s) from the supplied differentiating header. The other headers added by this method
* are related to CORS support.
*
* @param aHeader A differentiating header
* @return A list of headers, including the supplied header
*/
private static List<Header> getHeaders(final Header aHeader) {
return List.of(aHeader, new Header("Access-Control-Allow-Origin", "*"),
new Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"),
new Header("Access-Control-Allow-Headers", CONTENT_TYPE));
}
}
}

0 comments on commit 0a2e8f0

Please sign in to comment.