44import java .net .ServerSocket ;
55import java .net .Socket ;
66import java .util .HashMap ;
7+ import java .util .stream .Stream ;
8+ import java .nio .file .Files ;
79import java .nio .file .Path ;
810
911public 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 }
0 commit comments