Last active
March 14, 2024 12:42
-
-
Save bentech/0460da5e2b569ed38ed3756c5b1d8941 to your computer and use it in GitHub Desktop.
Grizzly Static Server SPA support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Bean | |
public RegisterableHttpHandler staticHttpHandler(GrizzlyProperties properties) { | |
File webDirectory = new File("web"); | |
StaticHttpHandler httpHandler = new StaticHttpHandler(webDirectory.getAbsolutePath()) { | |
// Serve index.html for non-existent files (for SPA routing support) | |
@Override | |
public void service(final Request request, final Response response) | |
throws Exception { | |
final String uri = getRelativeURI(request); | |
if (uri == null || !handle(uri, request, response)) { | |
if (isUriAFile(uri)) { | |
onMissingResource(request, response); | |
} else { | |
serveIndexHtml(response); | |
} | |
} | |
} | |
private void serveIndexHtml(final Response response) throws IOException { | |
File indexFile = new File(webDirectory, "index.html"); | |
response.setContentType("text/html"); | |
sendFile(response, indexFile); | |
} | |
private boolean isUriAFile(String uri) { | |
URI uriObj = URI.create(uri); | |
String path = uriObj.getPath(); | |
int lastSlashIndex = path.lastIndexOf('/'); | |
String lastSegment = path.substring(lastSlashIndex + 1); | |
// Consider it a file if there's a dot in the last segment, excluding cases where the dot is the first character | |
return lastSegment.contains(".") && !lastSegment.startsWith("."); | |
} | |
}; | |
httpHandler.setFileCacheEnabled(false); // Disable cache because it's very very slow | |
return new RegisterableHttpHandler(httpHandler, new HttpHandlerRegistration[]{ | |
HttpHandlerRegistration.fromString("/web/*"),}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment