|
| 1 | +package org.example; |
| 2 | + |
| 3 | +import org.example.http.HttpResponseBuilder; |
| 4 | + |
| 5 | +import java.io.File; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.OutputStream; |
| 8 | +import java.io.PrintWriter; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +public class StaticFileHandler { |
| 13 | + private final String WEB_ROOT; |
| 14 | + private byte[] fileBytes; |
| 15 | + private int statusCode; |
| 16 | + |
| 17 | + //Constructor for production |
| 18 | + public StaticFileHandler() { |
| 19 | + WEB_ROOT = "www"; |
| 20 | + } |
| 21 | + |
| 22 | + //Constructor for tests, otherwise the www folder won't be seen |
| 23 | + public StaticFileHandler(String webRoot){ |
| 24 | + WEB_ROOT = webRoot; |
| 25 | + } |
| 26 | + |
| 27 | + private void handleGetRequest(String uri) throws IOException { |
| 28 | + |
| 29 | + File file = new File(WEB_ROOT, uri); |
| 30 | + if(file.exists()) { |
| 31 | + fileBytes = Files.readAllBytes(file.toPath()); |
| 32 | + statusCode = 200; |
| 33 | + } else { |
| 34 | + File errorFile = new File(WEB_ROOT, "pageNotFound.html"); |
| 35 | + if(errorFile.exists()) { |
| 36 | + fileBytes = Files.readAllBytes(errorFile.toPath()); |
| 37 | + } else { |
| 38 | + fileBytes = "404 Not Found".getBytes(); |
| 39 | + } |
| 40 | + statusCode = 404; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public void sendGetRequest(OutputStream outputStream, String uri) throws IOException{ |
| 45 | + handleGetRequest(uri); |
| 46 | + |
| 47 | + HttpResponseBuilder response = new HttpResponseBuilder(); |
| 48 | + response.setStatusCode(statusCode); |
| 49 | + response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8")); |
| 50 | + response.setBody(fileBytes); |
| 51 | + PrintWriter writer = new PrintWriter(outputStream, true); |
| 52 | + writer.println(response.build()); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments