Skip to content

Commit

Permalink
Support OPTIONS method
Browse files Browse the repository at this point in the history
  • Loading branch information
jtulach committed Sep 18, 2021
1 parent 64bc0c4 commit 531c6e9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,11 @@ public RootPage(URL page) {
public <Request, Response> void service(HttpServer<Request, Response, ?, ?> server, Request rqst, Response rspns) throws IOException {
String path = server.getRequestURI(rqst);
cors(server, rspns);
if ("OPTIONS".equals(server.getMethod(rqst))) { // NOI18N
server.setStatus(rspns, 204);
server.addHeader(rspns, "Allow", "OPTIONS, GET, HEAD, POST, PUT"); // NOI18N
return;
}
if ("/".equals(path) || "index.html".equals(path)) {
Reader is;
String prefix = "http://" + server.getServerName(rqst) + ":" + server.getServerPort(rqst) + "/";
Expand Down Expand Up @@ -642,7 +647,9 @@ void service(Request rqst, Response rspns) throws IOException {
List<String> args = new ArrayList<>();
String body = server.getBody(rqst);
for (String p : body.split("&")) {
args.add(URLDecoder.decode(p.substring(3), "UTF-8"));
if (p.length() >= 3) {
args.add(URLDecoder.decode(p.substring(3), "UTF-8"));
}
}
String res;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ final class SimpleServer extends HttpServer<SimpleServer.ReqRes, SimpleServer.Re
private Selector connection;
private Thread processor;

private static final Pattern PATTERN_GET = Pattern.compile("(HEAD|GET|POST|PUT|DELETE) */([^ \\?]*)(\\?[^ ]*)?");
private static final Pattern PATTERN_GET = Pattern.compile("(OPTIONS|HEAD|GET|POST|PUT|DELETE) */([^ \\?]*)(\\?[^ ]*)?");
private static final Pattern PATTERN_HOST = Pattern.compile(".*^Host: *(.*):([0-9]+)$", Pattern.MULTILINE);
private static final Pattern PATTERN_LENGTH = Pattern.compile(".*^Content-Length: ([0-9]+)$", Pattern.MULTILINE);
static final Logger LOG = Logger.getLogger(SimpleServer.class.getName());
Expand Down Expand Up @@ -126,7 +126,11 @@ String getMethod(ReqRes r) {

@Override
String getBody(ReqRes r) {
return new String(r.body.array(), StandardCharsets.UTF_8);
if (r.body == null) {
return "";
} else {
return new String(r.body.array(), StandardCharsets.UTF_8);
}
}

static int endOfHeader(String header) {
Expand Down Expand Up @@ -597,7 +601,7 @@ public void handle(SelectionKey key, SocketChannel channel) throws IOException {
LOG.log(Level.FINER, "Written header, type {0}", mime);
bb = null;

if ("HEAD".equals(method)) {
if ("HEAD".equals(method) || "OPTIONS".equals(method)) {
LOG.fine("Writer flushed and closed, closing channel");
channel.close();
return;
Expand Down

0 comments on commit 531c6e9

Please sign in to comment.