LibJF/libjf-web-v1/src/main/java/io/gitlab/jfronny/libjf/web/impl/variant/shared/MainHttpHandlerImpl.java

39 lines
1.3 KiB
Java

package io.gitlab.jfronny.libjf.web.impl.variant.shared;
import io.gitlab.jfronny.libjf.mainhttp.api.v0.MainHttpHandler;
import io.gitlab.jfronny.libjf.mainhttp.api.v0.ServerState;
import io.gitlab.jfronny.libjf.web.api.v1.*;
import io.gitlab.jfronny.libjf.web.impl.JfWeb;
import io.gitlab.jfronny.libjf.web.impl.JfWebConfig;
import org.jetbrains.annotations.Nullable;
import java.io.*;
public class MainHttpHandlerImpl implements MainHttpHandler {
public MainHttpHandlerImpl() {
ServerState.onActivate(SharedWebServer::emitActive);
}
@Override
public boolean isActive() {
return JfWebConfig.port == -1;
}
@Override
public byte @Nullable [] handle(byte[] request) {
// Parse and process request
try (ByteArrayInputStream is = new ByteArrayInputStream(request);
HttpResponse response = JfWeb.getHandler().handle(HttpRequest.read(is))) {
if (response.getStatusCode() == HttpStatusCode.NOT_FOUND) return null;
// Write and send response
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
response.write(os);
os.flush();
return os.toByteArray();
}
} catch (IOException e) {
return null;
}
}
}