1818public class WebpackServer {
1919 private static final Logger log = LoggerFactory .getLogger (WebpackServer .class );
2020
21+ // {{start:routes}}
22+ // Simple not found 404 page
2123 public static void notFound (HttpServerExchange exchange ) {
2224 exchange .setStatusCode (404 );
2325 Exchange .body ().sendHtmlTemplate (exchange , "static/templates/src/notfound" , SimpleResponse .create ());
2426 }
2527
28+ // Default error page when something unexpected happens
2629 public static void error (HttpServerExchange exchange ) {
2730 exchange .setStatusCode (500 );
2831 Exchange .body ().sendHtmlTemplate (exchange , "static/templates/src/serverError" , SimpleResponse .create ());
@@ -34,7 +37,7 @@ public static void home(HttpServerExchange exchange) {
3437 Exchange .body ().sendHtmlTemplate (exchange , "static/templates/src/home" , SimpleResponse .create ());
3538 }
3639
37- // Render hello {name} page.
40+ // Render hello {name} page based on the name query param .
3841 public static void hello (HttpServerExchange exchange ) {
3942 exception (exchange );
4043 String name = Exchange .queryParams ()
@@ -46,18 +49,23 @@ public static void hello(HttpServerExchange exchange) {
4649 Exchange .body ().sendHtmlTemplate (exchange , "static/templates/src/hello" , response );
4750 }
4851
52+ // Helper function to forcibly throw an exception whenever the query
53+ // parameter exception=true
4954 private static void exception (HttpServerExchange exchange ) {
5055 if (Exchange .queryParams ().queryParamAsBoolean (exchange , "exception" ).orElse (false )) {
5156 throw new RuntimeException ("Poorly Named Exception!!!" );
5257 }
5358 }
59+ // {{end:routes}}
5460
5561 // {{start:server}}
62+ // We are currently handling all exceptions the same way
5663 private static HttpHandler exceptionHandler (HttpHandler next ) {
5764 return CustomHandlers .exception (next )
5865 .addExceptionHandler (Throwable .class , WebpackServer ::error );
5966 }
6067
68+ // Useful middleware
6169 private static HttpHandler wrapWithMiddleware (HttpHandler handler ) {
6270 return MiddlewareBuilder .begin (BlockingHandler ::new )
6371 .next (CustomHandlers ::gzip )
@@ -67,6 +75,8 @@ private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
6775 .complete (handler );
6876 }
6977
78+ // Simple routing, anything not matching a route will fall back
79+ // to the not found handler.
7080 private static final HttpHandler ROUTES = new RoutingHandler ()
7181 .get ("/" , WebpackServer ::home )
7282 .get ("/hello" , WebpackServer ::hello )
0 commit comments