2020
2121import java .io .*;
2222import java .net .InetSocketAddress ;
23+ import java .nio .file .Path ;
2324import java .util .*;
2425import java .util .concurrent .CompletableFuture ;
2526import java .util .concurrent .Future ;
@@ -40,6 +41,7 @@ public class Server implements HttpHandler {
4041 private final Map <String , String > csp = Collections .synchronizedMap (new HashMap <>());
4142 private final Map <String , HttpHandler > routes = Collections .synchronizedMap (new HashMap <>());
4243 private final Set <String > gzipRoutes = Collections .synchronizedSet (new HashSet <>());
44+ private java .nio .file .Path staticFilesDirectory ;
4345
4446 private static class Auth {
4547 public final String user ;
@@ -93,6 +95,10 @@ void enableGzip(String path) {
9395 gzipRoutes .add (path );
9496 }
9597
98+ void setStaticFilesDirectory (Path staticFilesDirectory ) {
99+ this .staticFilesDirectory = staticFilesDirectory ;
100+ }
101+
96102 static class Request {
97103 public final String url ;
98104 public final String method ;
@@ -187,7 +193,19 @@ public void handle(HttpExchange exchange) throws IOException {
187193 path = "/index.html" ;
188194 }
189195
190- // Resources from "src/test/resources/" are copied to "resources/" directory in the jar.
196+ // If static files directory is set, serve from filesystem first
197+ if (staticFilesDirectory != null ) {
198+ java .nio .file .Path filePath = staticFilesDirectory .resolve (path .substring (1 )); // Remove leading /
199+ if (java .nio .file .Files .exists (filePath ) && !java .nio .file .Files .isDirectory (filePath )) {
200+ exchange .getResponseHeaders ().add ("Content-Type" , mimeType (filePath .toFile ()));
201+ exchange .sendResponseHeaders (200 , java .nio .file .Files .size (filePath ));
202+ java .nio .file .Files .copy (filePath , exchange .getResponseBody ());
203+ exchange .getResponseBody ().close ();
204+ return ;
205+ }
206+ }
207+
208+ // Fallback: Resources from "src/test/resources/" are copied to "resources/" directory in the jar.
191209 String resourcePath = "resources" + path ;
192210 InputStream resource = getClass ().getClassLoader ().getResourceAsStream (resourcePath );
193211 if (resource == null ) {
0 commit comments