Skip to content

Commit 5162d75

Browse files
committed
Added StaticFileHandler from main
1 parent 5a685f3 commit 5162d75

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)