Skip to content

Commit 5af0394

Browse files
committed
404 page handler
1 parent 7a5fa99 commit 5af0394

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

lib/src/main/java/com/devsegal/jserve/BaseHTTPServer.java

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import java.net.ServerSocket;
55
import java.net.Socket;
66
import java.util.HashMap;
7+
import java.util.stream.Stream;
8+
import java.nio.file.Files;
79
import java.nio.file.Path;
810

911
public class BaseHTTPServer implements Runnable {
@@ -29,11 +31,47 @@ public void setupOriginalServerPath(String path) {
2931
setupOriginalServerPath(Path.of(path));
3032
}
3133

34+
// TODO: replace this method with more readable one and better structured
35+
// idea: put lambda in one function
36+
// TODO: allow nested folders in public asset folder
37+
public void setupPublicAssetFolder(Path assetFolder, String assetFolderPrefix) {
38+
Stream<Path> publicAssets = null;
39+
40+
try {
41+
publicAssets = Files.list(assetFolder);
42+
publicAssets.forEach(path -> {
43+
System.out.println(assetFolderPrefix + "/" + path.getFileName());
44+
45+
routesToHandlers.put(assetFolderPrefix + "/" + path.getFileName().toString() + "GET", (request, response) -> {
46+
response.setResponseHeaders(new ResponseHeaders("text/html", "close"));
47+
response.readContentFromFile(path, false);
48+
response.send();
49+
});
50+
});
51+
52+
} catch(IOException e) {
53+
e.printStackTrace();
54+
} finally {
55+
publicAssets.close();
56+
}
57+
}
58+
59+
public void setupPublicAssetFolder(Path assetFolder) {
60+
setupPublicAssetFolder(assetFolder, "");
61+
}
62+
63+
public void setupPublicAssetFolder(String path) {
64+
setupPublicAssetFolder(Path.of(path));
65+
}
66+
67+
public void setupPublicAssetFolder(String assetFolder, String assetFolderPrefix) {
68+
setupPublicAssetFolder(Path.of(assetFolder), assetFolderPrefix);
69+
}
70+
3271
public void setupNotFoundPageHandler(NotFoundPageHandler notFoundPageHandler) {
3372
this.notFoundPageHandler = notFoundPageHandler;
3473
}
3574

36-
3775
public void route(String path, String method, WebRouteHandler handler) {
3876
routesToHandlers.put(path + method, handler);
3977
}

lib/src/main/java/com/devsegal/jserve/ConnectionHandler.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ class ConnectionHandler implements Runnable {
1313
private BufferedReader requestReader;
1414
private ResponseWriter responseWriter;
1515
private Path originalServerPath;
16-
private Path publicAssetPath;
1716
private Socket connection;
1817
private NotFoundPageHandler notFoundPageHandler;
1918
private HashMap<String, WebRouteHandler> routesToHandlers;

0 commit comments

Comments
 (0)