|
| 1 | +package com.stubbornjava.examples.undertow.helloworld; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | + |
| 6 | +import io.undertow.Undertow; |
| 7 | +import io.undertow.server.HttpServerExchange; |
| 8 | +import io.undertow.util.Headers; |
| 9 | + |
| 10 | +public class HelloWorldServer { |
| 11 | + private static final Logger logger = LoggerFactory.getLogger(HelloWorldServer.class); |
| 12 | + |
| 13 | + /* |
| 14 | + * Creating HttpHandlers as a method and passing it as a method reference is pretty clean. |
| 15 | + * This also helps reduce accidentally adding state to handlers. |
| 16 | + */ |
| 17 | + public static void helloWorldHandler(HttpServerExchange exchange) { |
| 18 | + exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/plain"); |
| 19 | + exchange.getResponseSender().send("Hello World!"); |
| 20 | + } |
| 21 | + |
| 22 | + public static void main(String[] args) { |
| 23 | + int port = 8080; |
| 24 | + /* |
| 25 | + * "localhost" will ONLY listen on local host. |
| 26 | + * If you want the server reachable from the outside you need to set "0.0.0.0" |
| 27 | + */ |
| 28 | + String host = "localhost"; |
| 29 | + |
| 30 | + /* |
| 31 | + * If you really want to abstract out the server construction you can. |
| 32 | + * StubbornJava recommends to only use abstractions / wrappers on very simple APIs. |
| 33 | + * When you abstract over something like an HTTP server its very difficult to have |
| 34 | + * an abstraction that covers the nuances of each webserver. Instead accept it and let |
| 35 | + * the framework bleed out a bit. Realistically you shouldn't be changing your web server |
| 36 | + * all that often. Even if you did fully abstract it out your custom logic tends to bleed |
| 37 | + * out eventually, embrace it and move on. You could also just have a static method or |
| 38 | + * factory that created the server with your common configurations and allows further |
| 39 | + * customization later. |
| 40 | + */ |
| 41 | + Undertow server = Undertow.builder() |
| 42 | + // Add the helloWorldHandler as a method reference. |
| 43 | + .addHttpListener(port, host, HelloWorldServer::helloWorldHandler) |
| 44 | + .build(); |
| 45 | + logger.debug("starting on http://" + host + ":" + port); |
| 46 | + server.start(); |
| 47 | + } |
| 48 | +} |
0 commit comments