package io.undertow.server.handlers;
import java.util.Locale;
import java.util.Map;
import io.undertow.Handlers;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.CopyOnWriteMap;
import io.undertow.util.Headers;
public class NameVirtualHostHandler implements HttpHandler {
private volatile HttpHandler defaultHandler = ResponseCodeHandler.HANDLE_404;
private final Map<String, HttpHandler> hosts = new CopyOnWriteMap<>();
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final String hostHeader = exchange.getRequestHeaders().getFirst(Headers.HOST);
if (hostHeader != null) {
String host;
if (hostHeader.contains(":")) {
host = hostHeader.substring(0, hostHeader.lastIndexOf(":"));
} else {
host = hostHeader;
}
HttpHandler handler = hosts.get(host);
if (handler != null) {
handler.handleRequest(exchange);
return;
}
handler = hosts.get(host.toLowerCase(Locale.ENGLISH));
if (handler != null) {
handler.handleRequest(exchange);
return;
}
}
defaultHandler.handleRequest(exchange);
}
public HttpHandler getDefaultHandler() {
return defaultHandler;
}
public Map<String, HttpHandler> getHosts() {
return hosts;
}
public NameVirtualHostHandler setDefaultHandler(final HttpHandler defaultHandler) {
Handlers.handlerNotNull(defaultHandler);
this.defaultHandler = defaultHandler;
return this;
}
public synchronized NameVirtualHostHandler addHost(final String host, final HttpHandler handler) {
Handlers.handlerNotNull(handler);
hosts.put(host.toLowerCase(Locale.ENGLISH), handler);
return this;
}
public synchronized NameVirtualHostHandler removeHost(final String host) {
hosts.remove(host.toLowerCase(Locale.ENGLISH));
return this;
}
}