|
4 | 4 | import org.example.filter.IpFilter; |
5 | 5 | import org.example.httpparser.HttpParser; |
6 | 6 | import org.example.httpparser.HttpRequest; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.nio.file.NoSuchFileException; |
7 | 11 | import java.util.ArrayList; |
8 | 12 | import java.util.List; |
9 | 13 | import org.example.filter.Filter; |
@@ -69,19 +73,30 @@ public void runConnectionHandler() throws IOException { |
69 | 73 | // Check cache FIRST |
70 | 74 | byte[] cachedBytes = FileCache.get(cacheKey); |
71 | 75 | if (cachedBytes != null) { |
72 | | - System.out.println("✓ Cache HIT: " + sanitizedUri); |
73 | | - HttpResponseBuilder cachedResp = new HttpResponseBuilder(); |
74 | | - cachedResp.setContentTypeFromFilename(sanitizedUri); |
75 | | - cachedResp.setBody(cachedBytes); |
76 | | - client.getOutputStream().write(cachedResp.build()); |
| 76 | + System.out.println(" Cache HIT: " + sanitizedUri); |
| 77 | + response.setContentTypeFromFilename(sanitizedUri); |
| 78 | + response.setBody(cachedBytes); |
| 79 | + client.getOutputStream().write(response.build()); |
77 | 80 | client.getOutputStream().flush(); |
78 | 81 | return; |
79 | 82 | } |
80 | 83 |
|
81 | 84 | // Cache miss - StaticFileHandler reads and caches |
82 | | - System.out.println("✗ Cache MISS: " + sanitizedUri); |
83 | | - StaticFileHandler sfh = new StaticFileHandler(); |
84 | | - sfh.sendGetRequest(client.getOutputStream(), sanitizedUri); |
| 85 | + System.out.println(" Cache MISS: " + sanitizedUri); |
| 86 | + try { |
| 87 | + byte[] fileBytes = Files.readAllBytes(new File("www", sanitizedUri).toPath()); |
| 88 | + FileCache.put(cacheKey, fileBytes); // ← SPARAR I CACHEN HÄR |
| 89 | + |
| 90 | + response.setContentTypeFromFilename(sanitizedUri); |
| 91 | + response.setBody(fileBytes); |
| 92 | + client.getOutputStream().write(response.build()); |
| 93 | + client.getOutputStream().flush(); |
| 94 | + } catch (NoSuchFileException e) { |
| 95 | + response.setStatusCode(HttpResponseBuilder.SC_NOT_FOUND); |
| 96 | + response.setBody("404 Not Found"); |
| 97 | + client.getOutputStream().write(response.build()); |
| 98 | + client.getOutputStream().flush(); |
| 99 | + } |
85 | 100 | } |
86 | 101 |
|
87 | 102 | private String sanitizeUri(String uri) { |
|
0 commit comments