2020
2121import java .io .*;
2222import java .net .InetSocketAddress ;
23+ import java .nio .file .Files ;
24+ import java .nio .file .Path ;
2325import java .util .*;
2426import java .util .concurrent .CompletableFuture ;
2527import java .util .concurrent .Future ;
@@ -40,6 +42,7 @@ public class Server implements HttpHandler {
4042 private final Map <String , String > csp = Collections .synchronizedMap (new HashMap <>());
4143 private final Map <String , HttpHandler > routes = Collections .synchronizedMap (new HashMap <>());
4244 private final Set <String > gzipRoutes = Collections .synchronizedSet (new HashSet <>());
45+ private Path staticFilesDirectory ;
4346
4447 private static class Auth {
4548 public final String user ;
@@ -93,6 +96,10 @@ void enableGzip(String path) {
9396 gzipRoutes .add (path );
9497 }
9598
99+ void setStaticFilesDirectory (Path staticFilesDirectory ) {
100+ this .staticFilesDirectory = staticFilesDirectory ;
101+ }
102+
96103 static class Request {
97104 public final String url ;
98105 public final String method ;
@@ -187,7 +194,19 @@ public void handle(HttpExchange exchange) throws IOException {
187194 path = "/index.html" ;
188195 }
189196
190- // Resources from "src/test/resources/" are copied to "resources/" directory in the jar.
197+ // If static files directory is set, serve from filesystem first
198+ if (staticFilesDirectory != null ) {
199+ Path filePath = staticFilesDirectory .resolve (path .substring (1 )); // Remove leading /
200+ if (Files .exists (filePath ) && !Files .isDirectory (filePath )) {
201+ exchange .getResponseHeaders ().add ("Content-Type" , mimeType (filePath .toFile ()));
202+ exchange .sendResponseHeaders (200 , Files .size (filePath ));
203+ Files .copy (filePath , exchange .getResponseBody ());
204+ exchange .getResponseBody ().close ();
205+ return ;
206+ }
207+ }
208+
209+ // Fallback: Resources from "src/test/resources/" are copied to "resources/" directory in the jar.
191210 String resourcePath = "resources" + path ;
192211 InputStream resource = getClass ().getClassLoader ().getResourceAsStream (resourcePath );
193212 if (resource == null ) {
0 commit comments