-
-
Save eduard-vasinskyi/11b0774b317ff26483d47be1ecbd0aac to your computer and use it in GitHub Desktop.
An example of dynamic routing based on mime type
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 MimeTypeRoutingExample extends HttpServerLauncher { | |
private static final String IMAGE_TYPE_PREFIX = "image/"; | |
private static final String TEXT_TYPE_PREFIX = "text/"; | |
@Provides | |
AsyncServlet mainServlet(@Named("Image") AsyncServlet imageServlet, @Named("Text") AsyncServlet textServlet) { | |
return RoutingServlet.create() | |
.map("/*", request -> { | |
String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE); | |
if (contentType == null) { | |
return HttpResponse.ofCode(400).withPlainText("Content type is missing"); | |
} | |
if (isImageType(contentType)) { | |
return imageServlet.serve(request); | |
} else if (isTextType(contentType)) { | |
return textServlet.serve(request); | |
} else { | |
return HttpResponse.ofCode(400).withPlainText("Unsupported content type"); | |
} | |
}); | |
} | |
@Provides | |
@Named("Image") | |
AsyncServlet imageServlet() { | |
return request -> HttpResponse.ok200().withHtml("<h1>This servlet handles images</h1>"); | |
} | |
@Provides | |
@Named("Text") | |
AsyncServlet textServlet() { | |
return request -> HttpResponse.ok200().withHtml("<h1>This servlet handles text data</h1>"); | |
} | |
private static boolean isTextType(String mime) { | |
return mime.startsWith(TEXT_TYPE_PREFIX) && mime.length() > TEXT_TYPE_PREFIX.length(); | |
} | |
private static boolean isImageType(String mime) { | |
return mime.startsWith(IMAGE_TYPE_PREFIX) && mime.length() > IMAGE_TYPE_PREFIX.length(); | |
} | |
public static void main(String[] args) throws Exception { | |
new MimeTypeRoutingExample().launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment