MCPcopy Create free account
hub / github.com/CSpyridakis/notes / SimpleHttpServer

Class SimpleHttpServer

Java/Simple-http-server/SimpleHttpServer.java:11–41  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9import java.nio.file.Path;
10
11public class SimpleHttpServer {
12 public static void main(String[] args) throws IOException {
13 int port = 8080;
14 HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
15 server.createContext("/", new FileHandler());
16 server.setExecutor(null);
17 server.start();
18 System.out.println("Server started on port " + port);
19 }
20
21 static class FileHandler implements HttpHandler {
22 @Override
23 public void handle(HttpExchange exchange) throws IOException {
24 Path filePath = Path.of("index.html");
25 if (!Files.exists(filePath)) {
26 String response = "404 Not Found";
27 exchange.sendResponseHeaders(404, response.length());
28 try (OutputStream os = exchange.getResponseBody()) {
29 os.write(response.getBytes());
30 }
31 return;
32 }
33
34 byte[] fileBytes = Files.readAllBytes(filePath);
35 exchange.sendResponseHeaders(200, fileBytes.length);
36 try (OutputStream os = exchange.getResponseBody()) {
37 os.write(fileBytes);
38 }
39 }
40 }
41}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected