refactor: Use SimpleFileServer
All checks were successful
/ build (push) Successful in 27s

Instead of own HttpHandler

Signed-off-by: Minecon724 <git@m724.eu>
This commit is contained in:
Minecon724 2025-02-13 11:12:22 +01:00
parent 567bbd8c37
commit 3d4597b198
Signed by: Minecon724
GPG key ID: 3CCC4D267742C8E8

View file

@ -1,20 +1,18 @@
package eu.m724.blog; package eu.m724.blog;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
/** /**
* The {@code Server} class represents a basic HTTP server designed to serve files * The {@code Server} class represents a basic HTTP server designed to serve files
* from a specified webroot directory. * from a specified webroot directory.<br>
* {@link SimpleFileServer} is used.
*/ */
public class Server implements HttpHandler { public class Server {
private final Path webroot; private final Path webroot;
private InetSocketAddress listenAddress; private InetSocketAddress listenAddress;
@ -47,7 +45,7 @@ public class Server implements HttpHandler {
*/ */
public void start() throws IOException { public void start() throws IOException {
var server = HttpServer.create(listenAddress, 0); var server = HttpServer.create(listenAddress, 0);
server.createContext("/", this); server.createContext("/", SimpleFileServer.createFileHandler(webroot.toAbsolutePath()));
server.start(); server.start();
System.out.println("Server started on http:/" + server.getAddress()); System.out.println("Server started on http:/" + server.getAddress());
@ -70,27 +68,4 @@ public class Server implements HttpHandler {
System.out.println("Failed to open browser: " + e); System.out.println("Failed to open browser: " + e);
} }
} }
@Override
public void handle(HttpExchange exchange) throws IOException {
var path = webroot.resolve(exchange.getRequestURI().getPath().substring(1));
if (Files.isDirectory(path)) {
path = path.resolve("index.html");
}
var code = 404;
var content = "Not found".getBytes(StandardCharsets.UTF_8);
if (Files.isRegularFile(path)) {
code = 200;
content = Files.readAllBytes(path);
}
exchange.sendResponseHeaders(code, content.length);
var body = exchange.getResponseBody();
body.write(content);
body.close();
}
} }