|
| 1 | +package com.example.app; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | +import java.nio.charset.StandardCharsets; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import com.sun.net.httpserver.HttpExchange; |
| 9 | +import com.sun.net.httpserver.HttpHandler; |
| 10 | + |
| 11 | +public class StaticFileHandler implements HttpHandler { |
| 12 | + |
| 13 | + private static final Map<String, String> MIME_TYPES = Map.of( |
| 14 | + "html", "text/html; charset=utf-8", |
| 15 | + "css", "text/css; charset=utf-8", |
| 16 | + "js", "application/javascript; charset=utf-8", |
| 17 | + "json", "application/json; charset=utf-8", |
| 18 | + "png", "image/png", |
| 19 | + "svg", "image/svg+xml", |
| 20 | + "ico", "image/x-icon"); |
| 21 | + |
| 22 | + @Override |
| 23 | + public void handle(HttpExchange exchange) throws IOException { |
| 24 | + if (!"GET".equalsIgnoreCase(exchange.getRequestMethod())) { |
| 25 | + sendText(exchange, 405, "Method Not Allowed"); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + var requestUri = exchange.getRequestURI(); |
| 30 | + var rawPath = requestUri.getPath(); |
| 31 | + var path = (rawPath == null || "/".equals(rawPath)) ? "/index.html" : rawPath; |
| 32 | + |
| 33 | + if (path.contains("..")) { |
| 34 | + sendText(exchange, 400, "Bad Request"); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + var resourcePath = "/static" + path; |
| 39 | + try (InputStream stream = StaticFileHandler.class.getResourceAsStream(resourcePath)) { |
| 40 | + if (stream == null) { |
| 41 | + sendText(exchange, 404, "Not Found"); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + var bytes = stream.readAllBytes(); |
| 46 | + var headers = exchange.getResponseHeaders(); |
| 47 | + headers.set("Content-Type", resolveMimeType(path)); |
| 48 | + exchange.sendResponseHeaders(200, bytes.length); |
| 49 | + try (var output = exchange.getResponseBody()) { |
| 50 | + output.write(bytes); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private static void sendText(HttpExchange exchange, int statusCode, String payload) throws IOException { |
| 56 | + var bytes = payload.getBytes(StandardCharsets.UTF_8); |
| 57 | + exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); |
| 58 | + exchange.sendResponseHeaders(statusCode, bytes.length); |
| 59 | + try (var responseBody = exchange.getResponseBody()) { |
| 60 | + responseBody.write(bytes); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private static String resolveMimeType(String path) { |
| 65 | + int extensionIndex = path.lastIndexOf('.'); |
| 66 | + if (extensionIndex < 0 || extensionIndex == path.length() - 1) { |
| 67 | + return "application/octet-stream"; |
| 68 | + } |
| 69 | + var extension = path.substring(extensionIndex + 1).toLowerCase(); |
| 70 | + return MIME_TYPES.getOrDefault(extension, "application/octet-stream"); |
| 71 | + } |
| 72 | +} |
0 commit comments