io.github.kamilszewc.simplerouter.Route Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simple-java-http-router Show documentation
Show all versions of simple-java-http-router Show documentation
Simple Java router for building http services
package io.github.kamilszewc.simplerouter;
import java.util.HashMap;
import java.util.Map;
public class Route {
private final SimpleRouter.Method method;
private final String path;
private final MethodHandler methodHandler;
public Route(SimpleRouter.Method method, String path, MethodHandler methodHandler) {
this.method = method;
this.path = path;
this.methodHandler = methodHandler;
}
public String getPath() {
return path;
}
public SimpleRouter.Method getMethod() {
return method;
}
public static class RoutingContext {
private Request request;
private Map pathVariables = new HashMap<>();
public RoutingContext(Request request, Map pathVariables) {
this.request = request;
this.pathVariables = pathVariables;
}
public Request getRequest() {
return request;
}
public Map getPathVariables() {
return pathVariables;
}
}
public Object callMethod(RoutingContext routingContext) {
return methodHandler.handler(routingContext.getRequest(), routingContext.getPathVariables());
}
public RoutingContext checkRouting(Request request) throws NoRoutingException {
// First check if method fits
var requestMethod = request.getMethod();
if (method != requestMethod) {
throw new NoRoutingException();
}
// Get request path
var requestPath = request.getPath();
// Extract path elements
var requestPathElements = requestPath.split("/");
var pathElements = path.split("/");
Map pathVariables = new HashMap<>();
for (int i=0; i