diff --git a/Main.java b/Main.java index 4570b5b..8726425 100644 --- a/Main.java +++ b/Main.java @@ -4,6 +4,9 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -33,6 +36,7 @@ public class Main { } String request = requestBuilder.toString(); // System.out.println(request); + // PARSE THE REQUEST String[] requestLines = request.split("\r\n"); String[] requestLine = requestLines[0].split(" "); String method = requestLine[0]; @@ -52,14 +56,41 @@ public class Main { method, path, version, host, headers.toString()); System.out.println(accessLog); + Path filepath = getFilePath(path); + if (Files.exists(filepath)) { + // file exist + String contentType = guessContentType(filepath); + sendResponse(client, "200 OK", contentType, Files.readAllBytes(filepath)); + } else { + // 404 + byte[] notFoundContent = "

404 Something went wrong

".getBytes(); + sendResponse(client, "404 Not Found", "text/html", notFoundContent); + } + + } + + private static void sendResponse(Socket client, String status, String contentType, byte[] content) + throws IOException { OutputStream clientOutput = client.getOutputStream(); clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes()); clientOutput.write("ContentType: text/html\r\n".getBytes()); clientOutput.write("\r\n".getBytes()); - clientOutput.write("Hurray!!!1!".getBytes()); + clientOutput.write(content); + // These (windows) newlines indicate that the response is over clientOutput.write("\r\n\r\n".getBytes()); clientOutput.flush(); client.close(); } + private static String guessContentType(Path filepath) throws IOException { + return Files.probeContentType(filepath); + } + + private static Path getFilePath(String path) { + if ("/".equals(path)) { + path = "/index.html"; + } + return Paths.get("/home/andrzej/dev/java-http", path); + } + }