-
-
Save eduard-vasinskyi/608db17cc37b01888bdac0ad4d6b8dd4 to your computer and use it in GitHub Desktop.
An example of dynamic routing based on host
This file contains 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
package io.activej.launchers.http; | |
import io.activej.http.AsyncServlet; | |
import io.activej.http.HttpHeaders; | |
import io.activej.http.HttpResponse; | |
import io.activej.http.RoutingServlet; | |
import io.activej.inject.annotation.Named; | |
import io.activej.inject.annotation.Provides; | |
public final class HostRoutingExample extends HttpServerLauncher { | |
private static final String TEST_HOST = "test.com"; | |
private static final String EXAMPLE_HOST = "example.com"; | |
@Provides | |
AsyncServlet mainServlet(@Named("Test") AsyncServlet testServlet, @Named("Example") AsyncServlet exampleServlet) { | |
return RoutingServlet.create() | |
.map("/*", request -> { | |
String hostHeader = request.getHeader(HttpHeaders.HOST); | |
if (hostHeader == null) { | |
return HttpResponse.ofCode(400).withPlainText("Host header is missing"); | |
} | |
if (hostHeader.equals(TEST_HOST)) { | |
return testServlet.serve(request); | |
} else if (hostHeader.equals(EXAMPLE_HOST)) { | |
return exampleServlet.serve(request); | |
} else { | |
return HttpResponse.ofCode(400).withPlainText("Unknown host"); | |
} | |
}); | |
} | |
@Provides | |
@Named("Test") | |
AsyncServlet testServlet() { | |
return request -> HttpResponse.ok200().withHtml("<h1>This page is served on test.com</h1>"); | |
} | |
@Provides | |
@Named("Example") | |
AsyncServlet exampleServlet() { | |
return request -> HttpResponse.ok200().withHtml("<h1>This page is served on example.com</h1>"); | |
} | |
public static void main(String[] args) throws Exception { | |
new HostRoutingExample().launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment